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;
    }
}
相关推荐
ITKEY_14 小时前
appstore上架-预览和截屏
ios·appstore
阿捏利14 小时前
详解Mach-O(三十三)Mach-O __mod_term_func节
macos·ios·c/c++·mach-o
2501_9160074716 小时前
提高开发效率的尝试,用快蝎(kxapp)完成 iOS 项目的创建、调试与构建
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
2501_9151063217 小时前
如何在 Mac 上面代理抓包和数据流分析
android·macos·ios·小程序·uni-app·iphone·webview
blackorbird17 小时前
Coruna 间谍软件活动持续扩散,苹果破例为旧版iOS设备推送双版本安全补丁
macos·ios·objective-c·cocoa
for_ever_love__17 小时前
Objective-C 学习 单例模式
学习·ios·单例模式·objective-c
cola_wh17 小时前
避免团队多人 cocopods 冲突未验证
ios
2501_9159214317 小时前
在 Linux 上通过命令行上架 iOS APP,Fastlane + AppUploader(开心上架)
android·linux·运维·ios·小程序·uni-app·iphone
2501_9159214318 小时前
从构建到 IPA 保护,Flutter iOS 包如何做混淆与安全处理
android·安全·flutter·ios·小程序·uni-app·iphone
2501_9160088918 小时前
iPhone 手机硬件组件使用耗能历史记录查看,能耗查看
android·ios·智能手机·小程序·uni-app·iphone·webview