• iOS NSFileManager获取设备硬盘剩余可用容量不准确问题


    方法1. 通用
    NSFileManager attributesOfFileSystemForPath: error:

    方法2. available(iOS 11.0)
    NSURL resourceValuesForKeys: error:

    发现问题:方法1获取到的剩余值并不准确,测得使用剩余值远小于实际的手机存储容量剩余。所以使用方法2优先。下面代码中字典信息的Key值可以获取到对应的容量值。

    示例代码
     

    1. #import "UIDevice+DiskSpace.h"
    2. + (long)freeDiskSpaceInBytes
    3. {
    4. NSString *path = [MYPath document];
    5. NSError * error = nil;
    6. if (@available(iOS 11.0, *)) {
    7. NSURL * url = [[NSURL alloc]initFileURLWithPath:[NSString stringWithFormat:@"%@",path]];
    8. NSDictionary<NSURLResourceKey, id> * dict = [url resourceValuesForKeys:@[NSURLVolumeTotalCapacityKey,NSURLVolumeAvailableCapacityForImportantUsageKey] error:&error];
    9. if (error) {
    10. NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %@", [error domain], @([error code]));
    11. return 0;
    12. }
    13. uint64_t capacity = [dict[NSURLVolumeTotalCapacityKey] longLongValue];
    14. uint64_t freeSize = [dict[NSURLVolumeAvailableCapacityForImportantUsageKey] longLongValue];
    15. const uint64_t reserve = 200 * 1024 * 1024; /// 200m保留空间
    16. const CGFloat GB = 1024 * 1024 * 1024;
    17. NSLog(@"Memory Capacity of %.2f GB with %.2f GB Free memory available.", capacity / GB, (freeSize - reserve) / GB);
    18. return freeSize - reserve;
    19. } else {
    20. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:&error];
    21. if (attributes) {
    22. uint64_t capacity = [attributes[NSFileSystemSize] unsignedLongLongValue];
    23. uint64_t freeSize = [attributes[NSFileSystemFreeSize] unsignedLongLongValue];
    24. const uint64_t reserve = 200 * 1024 * 1024; /// 200m保留空间
    25. const CGFloat GB = 1024 * 1024 * 1024;
    26. NSLog(@"Memory Capacity of %.2f GB with %.2f GB Free memory available.", capacity / GB, (freeSize - reserve) / GB);
    27. return freeSize - reserve;
    28. }
    29. NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %@", [error domain], @([error code]));
    30. return 0;
    31. }
    32. }

  • 相关阅读:
    C++常用容器总结
    元宇宙的火爆让人们忽略了区块链的存在,这无益于元宇宙的发展
    Hadoop 集群小文件归档 HAR、小文件优化 Uber 模式
    Android组件通信——Intent(二十三)
    元宇宙基础概念
    flink---state详解
    Django——数据库
    vue2(1)
    .Net CLR GC 动态加载短暂堆阈值的计算及阈值超量的计算
    STL之优先级队列(priority_queue)
  • 原文地址:https://blog.csdn.net/u012812881/article/details/137924386