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.
for Swift as UIDevice extension
How to use:
Output will be:
Revised source using unsigned long long:
EDIT: it seems someone edited this code to use 'uint64_t' instead of 'unsigned long long'. While in the foreseeable future this should be just fine, they are not the same. 'uint64_t' is 64 bits and will always be that. In 10 years 'unsigned long long' might be 128. its a small point but why I used unsignedLongLong.
I have written a class to get available/used memory using Swift. Demo at: https://github.com/thanhcuong1990/swift-disk-status
Swift 4 updated.
Demo
Important clarification (at least for me). If I connect my iPod to my Mac this is the info showed by iTunes App.
When I use the above code:
The countStyle NSByteCountFormatterCountStyleFile show me: 17,41 GB
The countStyle NSByteCountFormatterCountStyleBinary show me: 16,22 GB
16,22 GB (NSByteCountFormatterCountStyleBinary) It is EXACTLY the number that iTunes App show me when I connect my iPod to my Mac.
ChrisJF answer in Swift 2.1 version:
Don't use 'unsigned', it is only 32 bits which will overflow past 4GB, which is less than the typical iPad/iPhone free space. Use unsigned long long (or uint64_t), and retrieve the value out of the NSNumber as a 64-bit int too using unsignedLongLongValue.