How to detect total available/free disk space on the iPhone/iPad device?

后端 未结 18 1948
别跟我提以往
别跟我提以往 2020-11-22 11:14

I\'m looking for a better way to detect available/free disk space on the iPhone/iPad device programmatically.
Currently I\'m using the NSFileManager to detect the disk s

18条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 11:40

    Swift 5 extension for FileManager with proper error handling and no automatic string conversions (convert byte count to string as you prefer). Also follows FileManager's naming.

    extension FileManager {
        func systemFreeSizeBytes() -> Result {
            do {
                let attrs = try attributesOfFileSystem(forPath: NSHomeDirectory())
                guard let freeSize = attrs[.systemFreeSize] as? Int64 else {
                    return .failure(NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Can't retrieve system free size"]))
                }
                return .success(freeSize)
            } catch {
                return .failure(error)
            }
        }
    
        func systemSizeBytes() -> Result {
             do {
                 let attrs = try attributesOfFileSystem(forPath: NSHomeDirectory())
                 guard let size = attrs[.systemSize] as? Int64 else {
                     return .failure(NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Can't retrieve system size"]))
                 }
                 return .success(size)
             } catch {
                 return .failure(error)
             }
         }
    }
    

    Example usage:

    let freeSizeResult = FileManager.default.systemFreeSizeBytes()
    switch freeSizeResult {
    case .failure(let error):
        print(error)
    case .success(let freeSize):
        let freeSizeString = ByteCountFormatter.string(fromByteCount: freeSize, countStyle: .file)
        print("free size: \(freeSizeString)")
    }
    

提交回复
热议问题