objective-c - iOS 9 / 10 -> 如何检查空闲/可用空间
问题描述
我尝试在目标 C 中检查 iOS 9 及更高版本上的可用空间。对于 iOS 11,这很容易: NSURLVolumeAvailableCapacityForImportantUsageKey 它工作正常!我得到 26GB。
但是对于 iOS 9 / 10,我不知道该怎么做。我试试这个功能:
//Get free space on the mobile
-(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;
}
但结果是错误的,我为同一设备获得了 18GB。
你有什么想法吗?
谢谢你 :)
解决方案
对于 iOS >= 6.0,您可以使用新的 NSByteCountFormatter。此代码以格式化字符串的形式获取剩余的空闲字节数。
NSError *error = nil;
NSArray * const paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSDictionary * const pathAttributes = [[NSFileManager defaultManager]
attributesOfFileSystemForPath:[paths firstObject] error:&error];
NSAssert(pathAttributes, @"");
NSNumber * const fileSystemSizeInBytes = [pathAttributes objectForKey:
NSFileSystemFreeSize];
const long long numberOfBytesRemaining = [fileSystemSizeInBytes longLongValue];
NSByteCountFormatter *byteCountFormatter = [[NSByteCountFormatter alloc] init];
NSString *formattedNmberOfBytesRemaining = [byteCountFormatter
stringFromByteCount:numberOfBytesRemaining];
推荐阅读
- ibm-cloud - 在我的资源列表中添加 Db2 时,它显示“您没有资源组”,所以我无法添加下一步该做什么?ibm-云
- python - 如何在python中显示Zingchart的反向y轴?
- postgresql - 如何在 Postgres 中识别和列出循环引用元素
- selenium-webdriver - 在 Functional Coverage 中,功能文件名在 serenity 报告上重复
- javascript - 我如何运行这个自定义 api?(使用 wix 和 javascript)
- reactjs - 前端应用程序的工作流管理系统
- python - 不断收到错误:lstm_8 层的输入 0 与该层不兼容:预期 ndim=3,发现 ndim=4。收到的完整形状:(无、94、94、32)
- javascript - 将 Jquery 转换为 Vanilla JS - 浮动元素
- excel - 为 Autocad 中的脚本目的寻找超过 32767 限制的方法
- android - 是否可以使用 Android Jetpack 创建具有不同参数的多个加密密钥?