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

方法1. 通用

NSFileManager attributesOfFileSystemForPath: error:

方法2. available(iOS 11.0)

NSURL resourceValuesForKeys: error:

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

示例代码:

复制代码
#import "UIDevice+DiskSpace.h"


+ (long)freeDiskSpaceInBytes
{
    NSString *path = [MYPath document];
    NSError * error = nil;
    if (@available(iOS 11.0, *)) {
        NSURL * url = [[NSURL alloc]initFileURLWithPath:[NSString stringWithFormat:@"%@",path]];
        NSDictionary<NSURLResourceKey, id> * dict = [url resourceValuesForKeys:@[NSURLVolumeTotalCapacityKey,NSURLVolumeAvailableCapacityForImportantUsageKey] error:&error];
        if (error) {
            NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %@", [error domain], @([error code]));
            return 0;
        }
        uint64_t capacity = [dict[NSURLVolumeTotalCapacityKey] longLongValue];
        uint64_t freeSize = [dict[NSURLVolumeAvailableCapacityForImportantUsageKey] longLongValue];
        const uint64_t reserve  = 200 * 1024 * 1024;                  /// 200m保留空间
        const CGFloat  GB       = 1024 * 1024 * 1024;
        NSLog(@"Memory Capacity of %.2f GB with %.2f GB Free memory available.", capacity / GB, (freeSize - reserve) / GB);
        return freeSize - reserve;
    } else {
        NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:&error];
        if (attributes) {
            uint64_t       capacity = [attributes[NSFileSystemSize] unsignedLongLongValue];
            uint64_t       freeSize = [attributes[NSFileSystemFreeSize] unsignedLongLongValue];
            const uint64_t reserve  = 200 * 1024 * 1024;                  /// 200m保留空间
            const CGFloat  GB       = 1024 * 1024 * 1024;
            NSLog(@"Memory Capacity of %.2f GB with %.2f GB Free memory available.", capacity / GB, (freeSize - reserve) / GB);
            return freeSize - reserve;
        }
        NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %@", [error domain], @([error code]));
        return 0;
    }
}
相关推荐
for_ever_love__7 小时前
UI学习:UISearchController基础了解和应用
学习·ui·ios·objective-c
代码的小搬运工12 小时前
ZARA仿写
ios
人月神话Lee14 小时前
【图像处理】vImage/Accelerate——SIMD 让 CPU 也能飞
ios·swift·图像识别
2601_9557674217 小时前
iPhone 17 护眼钢化膜怎么选?从PWM频闪到圆偏振光,解析「软硬协同」光学方案
ios·ar·iphone·护眼钢化膜·圆偏振光·#观复盾护景贴·磁控溅射
2601_9557674220 小时前
iPhone 17 护眼保护膜怎么选?圆偏振光 + AR 抗眩方案,解读 96% 透光率与 ≤0.5% 反射率的协同价值
ios·ar·iphone·圆偏振光·#观复盾护景贴·scinique双护技术
三雒21 小时前
KMP 实战:Android 开发如何快速统一双端 IM 模块
android·ios·kotlin
秋雨梧桐叶落莳1 天前
iOS——抽屉视图详解
开发语言·macos·ui·ios·objective-c·cocoa
库奇噜啦呼1 天前
【iOS】源码学习-方法交换
学习·ios·cocoa
hurrycry_小亦1 天前
苹果WWDC 2026前瞻:Ferret-Pro端侧大模型即将亮相|小亦之闻|AI 编程三日速递!(5月26日~5月28日)
macos·ios·wwdc
UTF_82 天前
一次NSMutableAttributedString误用的思考
ios·面试·github