I'm looking for a better way to detect available/free disk space on the iPhone/iPad device programmatically.
Currently I'm using the NSFileManager to detect the disk space. Following is the snippet of the code which does the job for me:
-(unsigned)getFreeDiskspacePrivate {
NSDictionary *atDict = [[NSFileManager defaultManager] attributesOfFileSystemForPath:@"/" error:NULL];
unsigned freeSpace = [[atDict objectForKey:NSFileSystemFreeSize] unsignedIntValue];
NSLog(@"%s - Free Diskspace: %u bytes - %u MiB", __PRETTY_FUNCTION__, freeSpace, (freeSpace/1024)/1024);
return freeSpace;
}
Am I correct with the above snippet? or is there any better way to know total available/free disk space.
I've to detect total free disk space, since we've to prevent our application to perform sync in the low disk space scenario.
If your looking to get the the remaining free space using Swift it is slightly different. You need to use attributesOfFileSystemForPath() instead of attributesOfItemAtPath():
Edit: Updated for Swift 1.0
Edit 2: Updated for safety, using Martin R's answer.
Edit 3: Updated for Swift 2.0 (by dgellow)
For iOS >= 6.0 you can use the new
NSByteCountFormatter
. This code gets the number of free bytes remaining as a formatted string.I know this post is a bit old, but I think this answer can help someone. If you want to know the used/free/total disk space on the device you can use Luminous. It's written in Swift. You have only to call :
or
Following code is Swift 3.0 version implementation of the answer previously provided by ChrisJF:
Update with a new accurate API to get available size on disk available in iOS11. Here is the description for the new API resource key:
I cross compared the results from key "FileAttributeKey.systemFreeSize" and key "URLResourceKey.volumeAvailableCapacityForImportantUsageKey" and found the results returned form "volumeAvailableCapacityForImportantUsageKey" exactly matches the available storage shown on UI. Here is the swift implementation:
Here's my answer and why it's better.
Answer (Swift):
Answer (Objective-C):
Why it's better:
NSByteCountFormatter
, meaning no crazy manual calculations from bytes to gigabytes. Apple does this for you!NSByteCountFormatter
does this for you. E.g. When the device's language is set to English the string will read 248.8 MB but will read 248,8 Mo when set to French, et cetera for other languages.