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;
    }
}
相关推荐
2501_916007472 小时前
Windows 怎么开发 Swift iOS App?SwiftUI 编译与真机调试和打包 ipa
ide·windows·vscode·ios·个人开发·swift·敏捷流程
iOS_MingXing10 小时前
iOS导航栏左上角显示一块白色圆角/圆形
macos·ios·cocoa
ii_best12 小时前
按键精灵和触动精灵哪个好?iOS 自动化选型的四个判断维度
运维·ios·自动化·按键精灵
乐鑫科技 Espressif13 小时前
通过 Wi-Fi Aware 直接将 ESP 设备连接到 iPhone——全新的跨平台 P2P 标准
ios·esp32·iphone·p2p·乐鑫科技
杜哥无敌1 天前
反向代理那些事儿: MaxKB 和1Panel ,用https还是http
ios·iphone
遥不可及zzz1 天前
iOS 27 适配指南:Xcode 27 升级、UIScene 生命周期迁移及游戏项目兼容性处理
ios·ios 27·xcode27
Geek-Chow2 天前
02 · Redux 是什么,又不是什么
ios
楚识科技2 天前
移动端 OCR SDK 集成拆解:Android/iOS 离线识别与结构化回填
android·ios·ocr
CocoaKier2 天前
神技分享:App加锁,App隐藏?苹果官方自带,只需要一个长按
ios·apple
传奇开心果编程3 天前
【六大移动UI框架比较学与练】第5课:交互与导航——事件处理、手势与页面路由实战对照
android·flutter·react native·ios·swiftui·移动开发·android jetpack