首页 > 解决方案 > 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。

你有什么想法吗?

谢谢你 :)

标签: objective-cios9ios10

解决方案


对于 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];

推荐阅读