如何检测iPhone / iPad设备上的总可用/可用磁盘空间? [英] How to detect total available/free disk space on the iPhone/iPad device?
问题描述
我正在寻找一种更好的方法来以编程方式检测iPhone / iPad设备上的可用/可用磁盘空间。
目前我正在使用NSFileManager来检测磁盘空间。以下是为我完成工作的代码片段:
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.
推荐答案
更新:由于此后已经过了很多时间已经添加了答案和新方法/ API,请查看以下更新的Swift等答案;由于我自己没有使用它们,我无法保证它们。
原始答案:
我发现以下解决方案适合我:
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;
}
它确切地返回了设备连接到机器时iTunes显示的大小。
It returns me exactly the size that iTunes displays when device is connected to machine.
这篇关于如何检测iPhone / iPad设备上的总可用/可用磁盘空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!