如何在 swift 2.0 中使用 AttributesOfFileSystemForpaths 获取总磁盘空间和可用磁盘空间

Posted

技术标签:

【中文标题】如何在 swift 2.0 中使用 AttributesOfFileSystemForpaths 获取总磁盘空间和可用磁盘空间【英文标题】:How to get the Total Disk Space and Free Disk space using AttributesOfFileSystemForpaths in swift 2.0 【发布时间】:2016-03-15 09:05:51 【问题描述】:

这是我在 Objective-C 中使用的方式

-(uint64_t)getFreeDiskspace 
float totalSpace = 0;
float totalFreeSpace = 0;
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];

if (dictionary) 
    NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
    NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
    totalSpace = [fileSystemSizeInBytes floatValue];
    self.totalSpace = [NSString stringWithFormat:@"%.3f GB",totalSpace/(1024*1024*1024)];
    totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
    self.freeSpace = [NSString stringWithFormat:@"%.3f GB",totalFreeSpace/(1024*1024*1024)];

 else 
    LogError(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);


return totalFreeSpace;

我尝试将其转换为 swift 和错误

if(dictionary)

attributesOfFileSystemForPaths 

已显示。任何人都可以帮助我将其转换为 swift 2.0 吗?这将对我的项目大有裨益。提前谢谢你。

【问题讨论】:

I tried converting it to swift 请出示您的版本,我们可以帮助您修复它。 感谢您的回复 Eric.D。我没有完全转换它。并且最初的行中有错误,所以我浪费了大量时间调试但无法使其工作..所以请您转换它并让我知道它是如何完成的? 我删了。但是等一下,我会重写方法,然后给你报错 Eric。 【参考方案1】:

对于 Swift 5.1.3:

struct FileManagerUility 

    static func getFileSize(for key: FileAttributeKey) -> Int64? 
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)

        guard
            let lastPath = paths.last,
            let attributeDictionary = try? FileManager.default.attributesOfFileSystem(forPath: lastPath) else  return nil 

        if let size = attributeDictionary[key] as? NSNumber 
            return size.int64Value
         else 
            return nil
        
    

    static func convert(_ bytes: Int64, to units: ByteCountFormatter.Units = .useGB) -> String? 
        let formatter = ByteCountFormatter()
        formatter.allowedUnits = units
        formatter.countStyle = ByteCountFormatter.CountStyle.decimal
        formatter.includesUnit = false
        return formatter.string(fromByteCount: bytes)
    


像这样使用 api:

 if let totalSpaceInBytes = FileManagerUility.getFileSize(for: .systemSize) 
    /// If you want to convert into GB then call like this
    let totalSpaceInGB = FileManagerUility.convert(totalSpaceInBytes)
    print("Total space [\(totalSpaceInBytes) bytes] = [\(totalSpaceInGB!) GB]")



if let freeSpaceInBytes = FileManagerUility.getFileSize(for: .systemFreeSize) 
    /// If you want to convert into GB then call like this
    let freeSpaceInGB = FileManagerUility.convert(freeSpaceInBytes)
    print("Free space [\(freeSpaceInBytes) bytes] = [\(freeSpaceInGB!) GB]")

【讨论】:

【参考方案2】:

更新 Swift 3 @Md.Muzahidul Islam

func getFreeSize() -> Int64? 
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        if let dictionary = try? FileManager.default.attributesOfFileSystem(forPath: paths.last!) 
            if let freeSize = dictionary[FileAttributeKey.systemFreeSize] as? NSNumber 
                return freeSize.int64Value
            
        else
            print("Error Obtaining System Memory Info:")
        
        return nil
    

    func getTotalSize() -> Int64?
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        if let dictionary = try? FileManager.default.attributesOfFileSystem(forPath: paths.last!) 
            if let freeSize = dictionary[FileAttributeKey.systemSize] as? NSNumber 
                return freeSize.int64Value
            
        else
            print("Error Obtaining System Memory Info:")
        
        return nil
    

【讨论】:

【参考方案3】:

更新 Swift-4

func getFreeDiskspace() -> Int64? 
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        if let dictionary = try? FileManager.default.attributesOfFileSystem(forPath: paths.last!) 
            if let freeSize = dictionary[FileAttributeKey.systemFreeSize] as? NSNumber 
                return freeSize.int64Value
            
        else
            print("Error Obtaining System Memory Info:")
        
        return nil
    

if let getFreespace = getFreeDiskspace() 
   print(getFreespace) // free disk space

【讨论】:

以上是关于如何在 swift 2.0 中使用 AttributesOfFileSystemForpaths 获取总磁盘空间和可用磁盘空间的主要内容,如果未能解决你的问题,请参考以下文章