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;
    }
}
相关推荐
茶底世界之下18 小时前
洗衣房的午后斜光:用 Awaking 把光和影分开
ios·app·产品
我是谁的程序员2 天前
iOS 性能分析在 Windows 上怎么做,用 KXBuild 的 kxdevice 替代 Instruments
后端·ios
开心就好20252 天前
通配符 Bundle ID 和精确 Bundle ID 怎么选,推送、iCloud 能不能用通配符
后端·ios
布莱克6052 天前
Swift 枚举详解:从基础语法到关联值与模式匹配
开发语言·ios·swift·枚举
茶底世界之下2 天前
冬日窗边的早餐:用 Awaking 留住冷光里的暖意
ios·app·产品
布莱克6052 天前
Swift 闭包详解:从语法到实战的完整指南
服务器·开发语言·ios·ssh·swift·闭包
茶底世界之下3 天前
雨后的黄电车:用 Awaking 给灰色街景定一个主角
ios·app·产品
恋猫de小郭3 天前
iOS for Web ,把原生 iOS App 跑到进浏览器里面,倒反天罡
android·前端·ios
00后程序员3 天前
iOS 实时活动怎么开发,Windows 上用 KXBuild 和 ActivityKit 写灵动岛
后端·ios
iReaShare4 天前
如何在没有 Wi-Fi 的情况下备份 iPhone
ios