【问题标题】:NSFileSystemFreeSize returning inaccurate free disk space?NSFileSystemFreeSize 返回不准确的可用磁盘空间?
【发布时间】:2018-07-06 04:07:45
【问题描述】:

所以我正在尝试查找我的 iPhone 上的可用磁盘空间量,并且我已经搜索了几篇较早的帖子。这些帖子中的大多数使用 NSFileManager 来检索 NSFileSystemFreeSize 值。

但是,与我在手机设置>常规>关于>可用中看到的数字相比,来自 NSFileSystemFreeSize 的数字似乎不准确。

我得到以下值:

  • NSFileSystemFreeSize:2287063040 (~2.28 GB)
  • 手机可用设置:5.77 GB
  • iTunes:5.67 GB 免费

我使用的代码:

+ (NSString*)getFreeDiskspace
{
NSDictionary *atDict = [[NSFileManager defaultManager] attributesOfFileSystemForPath:@"/" error:NULL];
unsigned freeSpace = [[atDict objectForKey:NSFileSystemFreeSize] unsignedIntValue];

return [NSString stringWithFormat:@"%u", freeSpace];
}

其他信息:

  • 使用手机:iPhone 7
  • 操作系统版本 11.2.1
  • 手机已插入 macbook,因此我可以直接通过 xCode 构建

谁能向我解释为什么 NSFileSystemFreeSize 与手机和 iTunes 不匹配?任何帮助表示赞赏,谢谢!

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    有很多方法可以获得空闲空间

    1、

    NSString *tempDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary<NSFileAttributeKey, id> *att = [fileManager attributesOfFileSystemForPath:tempDir error:nil];
    NSNumber *freeSize = att[NSFileSystemFreeSize];
    const long long freeSpace = [freeSize longLongValue];
    

    2、仅iOS 11或更高版本

    NSURL *url = [[NSURL alloc] initFileURLWithPath:NSHomeDirectory()];
    id AA = [url resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:nil][NSURLVolumeAvailableCapacityForImportantUsageKey];
    NSLog(@"\nURLVolumeAvailableCapacityForImportantUsage : -----------\n%@", AA);
    

    3、f_bavail或f_bfree供使用

    - (const long long) diskSpace {
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    struct statfs tStats;
    statfs([[paths lastObject] cStringUsingEncoding:NSUTF8StringEncoding], &tStats);
    
    // for total space
    //    const long long total_space = (long long)(tStats.f_blocks * tStats.f_bsize);
    //    return total_space;
    
    // for freespace:
    const long long free_space = (long long)(tStats. f_bavail * tStats.f_bsize);
    return free_space;
    

    }

    【讨论】:

      【解决方案2】:

      试试用 unsignedLongLongValue 代替 unsignedIntValue?

      【讨论】:

        【解决方案3】:

        iOS 设置 UI 不会报告可用的“真实”可用空间。因为操作系统可以请求存储在Library/Caches/tmp/ 中的所有内容,所以它被视为可用空间。 同样在 UI 中,尺寸以 10 为底而不是以 2 为底显示。

        【讨论】:

          猜你喜欢
          • 2014-08-06
          • 1970-01-01
          • 2019-12-12
          • 1970-01-01
          • 2010-11-26
          • 2011-02-19
          • 1970-01-01
          • 2012-11-15
          • 1970-01-01
          相关资源
          最近更新 更多