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;
    }
}
相关推荐
若水无华9 小时前
fiddler 配置ios手机代理调试
ios·智能手机·fiddler
Aress"10 小时前
【ios越狱包安装失败?uniapp导出ipa文件如何安装到苹果手机】苹果IOS直接安装IPA文件
ios·uni-app·ipa安装
Jouzzy20 小时前
【iOS安全】Dopamine越狱 iPhone X iOS 16.6 (20G75) | 解决Jailbreak failed with error
安全·ios·iphone
瓜子三百克20 小时前
采用sherpa-onnx 实现 ios语音唤起的调研
macos·ios·cocoa
左钦杨21 小时前
IOS CSS3 right transformX 动画卡顿 回弹
前端·ios·css3
努力成为包租婆1 天前
SDK does not contain ‘libarclite‘ at the path
ios
安和昂2 天前
【iOS】Tagged Pointer
macos·ios·cocoa
I烟雨云渊T2 天前
iOS 阅后即焚功能的实现
macos·ios·cocoa
struggle20252 天前
适用于 iOS 的 开源Ultralytics YOLO:应用程序和 Swift 软件包,用于在您自己的 iOS 应用程序中运行 YOLO
yolo·ios·开源·app·swift
Unlimitedz2 天前
iOS视频编码详细步骤(视频编码器,基于 VideoToolbox,支持硬件编码 H264/H265)
ios·音视频