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.
To check your iPhone's storage on any iOS version, go to Settings > General > [Your Device Name] Storage > About > Capacity.
To see how much cellular data you've used, go to Settings > Cellular or Settings > Mobile Data. If you're using an iPad, you might see Settings > Cellular Data instead. Scroll down to find which apps are using cellular data. If you don't want an app to use cellular data, you can turn it off for that app.
UPDATE: Since a lot of time has passed after this answer and new methods/APIs have been added, please check the updated answers below for Swift etc; Since I've not used them myself, I can't vouch for them.
Original answer: I found the following solution working for me:
-(uint64_t)getFreeDiskspace { uint64_t totalSpace = 0; uint64_t totalFreeSpace = 0; NSError *error = nil; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error]; if (dictionary) { NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize]; NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize]; totalSpace = [fileSystemSizeInBytes unsignedLongLongValue]; totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue]; NSLog(@"Memory Capacity of %llu MiB with %llu MiB Free memory available.", ((totalSpace/1024ll)/1024ll), ((totalFreeSpace/1024ll)/1024ll)); } else { NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]); } return totalFreeSpace; }
It returns me exactly the size that iTunes displays when device is connected to machine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With