美文网首页iOS开发那点儿事
iOS 获取设备剩余空间、已使用空间、总空间的正确姿势(Swif

iOS 获取设备剩余空间、已使用空间、总空间的正确姿势(Swif

作者: Cingjin | 来源:发表于2021-08-11 18:11 被阅读0次

    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 获取设备磁盘总容量
     * @return 单位GB
     */
    + (NSString *)totalDiskSpaceInGB;
    /**
     * @abstract 获取设备磁盘总容量
     * @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地址

    相关文章

      网友评论

        本文标题:iOS 获取设备剩余空间、已使用空间、总空间的正确姿势(Swif

        本文链接:https://www.haomeiwen.com/subject/tficbltx.html