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;
    }
}
相关推荐
Mr_CrazyPeter12 小时前
【无标题】
ios·模拟器·ons
yuananyun16 小时前
APP 图标规范与设计全攻略:iOS/Android/Web 一次设计多端合规,快速出图
android·前端·ios
niech_cn17 小时前
uniapp开发App(iOS、Android、鸿蒙Next)之配置pages.json 页面路由(三)
android·ios·uni-app
游戏开发爱好者819 小时前
Linux 自动上传 App Store Connect:把 IPA 上传流程接进CI工作流
linux·运维·ios·ci/cd·小程序·uni-app·iphone
白玉cfc19 小时前
【iOS】底层原理:方法交换
macos·ios·cocoa
暗冰ཏོ20 小时前
2026 App 开发完整指南:Android、iOS、跨平台开发与安卓应用上线全流程
android·ios·uni-app·web app·app开发
人月神话-Lee2 天前
【图像处理】图像直方图——从“频率分布“到“智能决策“
图像处理·人工智能·ios·ai编程·swift
会Tk矩阵群控的小木2 天前
imessage虚拟机群发系统搭建:基于UTM+Frida的完整实现与海外社媒集成
macos·ios·objective-c·cocoa·开源软件·个人开发·tk矩阵
灰鲸广告联盟2 天前
新老用户广告价值不同?差异化策略如何实现收益最大化
android·开发语言·flutter·ios