iOS 獲取設備剩余空間、已使用空間、總空間的正確姿勢(Swift + OC)

Swift

extension UIDevice {
    
    func MBFormatter(_ bytes: Int64) -> String {
        let formatter = ByteCountFormatter()
        formatter.allowedUnits = ByteCountFormatter.Units.useMB
        formatter.countStyle = ByteCountFormatter.CountStyle.decimal
        formatter.includesUnit = false
        return formatter.string(fromByteCount: bytes) as String
    }
    
    //MARK: Get String Value
    var totalDiskSpaceInGB:String {
       return ByteCountFormatter.string(fromByteCount: totalDiskSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.decimal)
    }
    
    var freeDiskSpaceInGB:String {
        return ByteCountFormatter.string(fromByteCount: freeDiskSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.decimal)
    }
    
    var usedDiskSpaceInGB:String {
        return ByteCountFormatter.string(fromByteCount: usedDiskSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.decimal)
    }
    
    var totalDiskSpaceInMB:String {
        return MBFormatter(totalDiskSpaceInBytes)
    }
    
    var freeDiskSpaceInMB:String {
        return MBFormatter(freeDiskSpaceInBytes)
    }
    
    var usedDiskSpaceInMB:String {
        return MBFormatter(usedDiskSpaceInBytes)
    }
    
    //MARK: Get raw value
    var totalDiskSpaceInBytes:Int64 {
        guard let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String),
            let space = (systemAttributes[FileAttributeKey.systemSize] as? NSNumber)?.int64Value else { return 0 }
        return space
    }
    
    /*
     Total available capacity in bytes for "Important" resources, including space expected to be cleared by purging non-essential and cached resources. "Important" means something that the user or application clearly expects to be present on the local system, but is ultimately replaceable. This would include items that the user has explicitly requested via the UI, and resources that an application requires in order to provide functionality.
     Examples: A video that the user has explicitly requested to watch but has not yet finished watching or an audio file that the user has requested to download.
     This value should not be used in determining if there is room for an irreplaceable resource. In the case of irreplaceable resources, always attempt to save the resource regardless of available capacity and handle failure as gracefully as possible.
     */
    var freeDiskSpaceInBytes:Int64 {
        if #available(iOS 11.0, *) {
            if let space = try? URL(fileURLWithPath: NSHomeDirectory() as String).resourceValues(forKeys: [URLResourceKey.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage {
                return space
            } else {
                return 0
            }
        } else {
            if let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String),
            let freeSpace = (systemAttributes[FileAttributeKey.systemFreeSize] as? NSNumber)?.int64Value {
                return freeSpace
            } else {
                return 0
            }
        }
    }
    
    var usedDiskSpaceInBytes:Int64 {
       return totalDiskSpaceInBytes - freeDiskSpaceInBytes
    }
}

使用

    UIDevice.current.totalDiskSpaceInGB
    UIDevice.current.freeDiskSpaceInGB
    UIDevice.current.usedDiskSpaceInGB

Swift參考地址

OC

UIDevice+DiskSpace.h


/**
 * @abstract 獲取設備磁盤總?cè)萘? * @return 單位GB
 */
+ (NSString *)totalDiskSpaceInGB;
/**
 * @abstract 獲取設備磁盤總?cè)萘? * @return 單位M
 */
+ (NSString *)totalDiskSpaceInMB;
/**
 * @abstract 獲取設備磁盤空余容量
 * @return 單位GB
 */
+ (NSString *)freeDiskSpaceInGB;
/**
 * @abstract 獲取設備磁盤空余容量
 * @return 單位M
 */
+ (NSString *)freeDiskSpaceInMB;
/**
 * @abstract 獲取設備磁盤已使用量
 * @return 單位GB
 */
+ (NSString *)usedDiskSpaceInGB;
/**
 * @abstract 獲取設備磁盤已使用量
 * @return 單位M
 */
+ (NSString *)usedDiskSpaceInMB;

UIDevice+DiskSpace.m

+ (NSString *)totalDiskSpaceInGB
{
    return [NSByteCountFormatter stringFromByteCount:self.totalDiskSpaceInBytes countStyle:NSByteCountFormatterCountStyleDecimal];
}

+ (NSString *)totalDiskSpaceInMB
{
    return [self MBFormatter:self.totalDiskSpaceInBytes];
}

+ (NSString *)freeDiskSpaceInGB
{
    return [NSByteCountFormatter stringFromByteCount:self.freeDiskSpaceInBytes countStyle:NSByteCountFormatterCountStyleDecimal];
}

+ (NSString *)freeDiskSpaceInMB
{
    return [self MBFormatter:self.freeDiskSpaceInBytes];
}

+ (NSString *)usedDiskSpaceInGB
{
    return [NSByteCountFormatter stringFromByteCount:self.usedDiskSpaceInBytes countStyle:NSByteCountFormatterCountStyleDecimal];
}

+ (NSString *)usedDiskSpaceInMB
{
    return [self MBFormatter:self.usedDiskSpaceInBytes];
}

+ (NSString *)MBFormatter:(long long)byte
{
    NSByteCountFormatter * formater = [[NSByteCountFormatter alloc]init];
    formater.allowedUnits = NSByteCountFormatterUseGB;
    formater.countStyle = NSByteCountFormatterCountStyleDecimal;
    formater.includesUnit = false;
    return [formater stringFromByteCount:byte];
}

+ (long)totalDiskSpaceInBytes
{
    NSError * error = nil;
    NSDictionary<NSFileAttributeKey, id> * systemAttributes =  [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
    if (error) {
        return 0;
    }
    long long space = [systemAttributes[NSFileSystemSize] longLongValue];
    return space;
}

+ (long)freeDiskSpaceInBytes
{
    if (@available(iOS 11.0, *)) {
        [NSURL alloc];
        NSURL * url = [[NSURL alloc]initFileURLWithPath:[NSString stringWithFormat:@"%@",NSHomeDirectory()]];
        NSError * error = nil;
        NSDictionary<NSURLResourceKey, id> * dict = [url resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:&error];
        if (error) {
            return 0;
        }
        long long space = [dict[NSURLVolumeAvailableCapacityForImportantUsageKey] longLongValue];
        return space;
    } else {
        NSError * error = nil;
        NSDictionary<NSFileAttributeKey, id> * systemAttributes =  [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
        if (error) {
            return 0;
        }
        long long space = [systemAttributes[NSFileSystemFreeSize] longLongValue];
        return space;
    }
}

+ (long)usedDiskSpaceInBytes
{
    return self.totalDiskSpaceInBytes - self.freeDiskSpaceInBytes;
}

使用

UIDevice.totalDiskSpaceInGB
UIDevice.freeDiskSpaceInGB
UIDevice.usedDiskSpaceInGB

Demo地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容