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;
    }
}
相关推荐
键盘敲没电42 分钟前
【IOS】GCD学习
学习·ios·objective-c·xcode
SY.ZHOU1 小时前
Significant Location Change
macos·ios·cocoa
吴Wu涛涛涛涛涛Tao8 小时前
深入理解 Swift Codable:从基础到进阶
ios
Jouzzy14 小时前
【iOS安全】iPhone X iOS 16.7.11 (20H360) WinRa1n 越狱教程
安全·ios·iphone
二流小码农1 天前
鸿蒙开发:实现一个标题栏吸顶
android·ios·harmonyos
season_zhu1 天前
iOS开发:关于日志框架
ios·架构·swift
Digitally1 天前
如何在电脑上轻松访问 iPhone 文件
ios·电脑·iphone
安和昂1 天前
【iOS】YYModel源码解析
ios
pop_xiaoli1 天前
UI学习—cell的复用和自定义cell
学习·ui·ios
Daniel_Coder1 天前
Xcode 16.4 + iOS 18 系统运行时崩溃:___cxa_current_primary_exception 符号丢失的原因与解决方案
ios·xcode·ios 18·dyld·libc++abi