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
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)")
}