【问题标题】:iOS 9 / 10 -> how to check free / available spaceiOS 9 / 10 -> 如何检查可用/可用空间
【发布时间】:2019-05-07 08:17:51
【问题描述】:

我尝试在目标 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-c ios9 ios10


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 1970-01-01
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多