簡體   English   中英

如何使用 swift 2.0 中的 AttributesOfFileSystemForpaths 獲取總磁盤空間和可用磁盤空間

[英]How to get the Total Disk Space and Free Disk space using AttributesOfFileSystemForpaths in swift 2.0

這是我在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 嗎? 它會對我的項目大有裨益。 先感謝您。

對於 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]")
}

更新 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
    }

更新 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
}

此處發布的其他答案中的技術對我不起作用。 他們返回的可用空間量大大低於我設備上的可用空間。 我相信獲得可用空間量的正確方法是這樣做:

func deviceRemainingFreeSpaceInBytes() -> Int64? {
    let url = URL(filePath: "/")
    let results = try? url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
    return results?.volumeAvailableCapacityForImportantUsage
}

取自此處Apple的示例並轉換為Swift。https://developer.apple.com/documentation/foundation/nsurlresourcekey/checking_volume_storage_capacity

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM