Mathi Arasan
Mathi Arasan

Reputation: 889

How to get storage and memory size of my iOS Application?

In my case want to show an alert when my application storage space reaches a certain level. I saw some of the code in StackOverflow mention

  1. clear temp cache memory and image from the web
  2. Get over all storage memory size
  3. RAM size, ect.,

I didn't find anything related what I want. If I miss anything point out that.

Simple and clear: Want storage size for my application, like Android show application storage occupied Size (In setting)

Update 1:

Go to Settings > General > Storage & iCloud Usage > Manage Storage My app show 20 MB also that mention Documents 7 Data

-(natural_t) get_free_memory {
mach_port_t host_port;
mach_msg_type_number_t host_size;
vm_size_t pagesize;
host_port = mach_host_self();
host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
host_page_size(host_port, &pagesize);
vm_statistics_data_t vm_stat;

if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {
    NSLog(@"Failed to fetch vm statistics");
    return 0;
}

/* Stats in bytes */
natural_t mem_free = vm_stat.free_count * pagesize;
NSLog(@"mem_free %u", mem_free);
return mem_free;
}

I am using this code to check this one also give around 20 MB. But I got this code as to get free memory. Actually is that to get the free memory or to get application memory.

Upvotes: 2

Views: 2073

Answers (1)

Sudipto Roy
Sudipto Roy

Reputation: 6795

To get storage info use the code below ( Swift 5) .

//
//  Storage.swift
//  BCScanner2
//
//  Created by Admin on 2017-07-11.
//  Copyright © 2017 com.odyssey. All rights reserved.
//

import Foundation

class Storage
{

    static func getFreeSpace() -> Int64
    {
        do
        {
            let attributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory())

            return attributes[FileAttributeKey.systemFreeSize] as! Int64
        }
        catch
        {
            return 0
        }
    }

    static func getTotalSpace() -> Int64
    {
        do {
            let attributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory())
            return attributes[FileAttributeKey.systemFreeSize] as! Int64
        } catch {
            return 0
        }
    }

    static func getUsedSpace() -> Int64
    {
        return getTotalSpace() - getFreeSpace()
    }




}




extension Int64
{
    func toMB() -> String {
        let formatter = ByteCountFormatter()
        formatter.allowedUnits = ByteCountFormatter.Units.useMB
        formatter.countStyle = ByteCountFormatter.CountStyle.decimal
        formatter.includesUnit = false
        return formatter.string(fromByteCount: self) as String
    }
}

And call like . .

print(Storage.getTotalSpace().toMB())
print(Storage.getFreeSpace().toMB())
print(Storage.getUsedSpace().toMB())

Upvotes: 3

Related Questions