I am trying to get the size of a directory, as well as it\'s content on OS X using Swift. So far, I have only been able to get the size of the directory itself, with none of
For anyone looking for the barebones implementation (works the same on macOS and iOS):
Swift 5 barebones version
extension URL {
var fileSize: Int? { // in bytes
do {
let val = try self.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey])
return val.totalFileAllocatedSize ?? val.fileAllocatedSize
} catch {
print(error)
return nil
}
}
}
extension FileManager {
func directorySize(_ dir: URL) -> Int? { // in bytes
if let enumerator = self.enumerator(at: dir, includingPropertiesForKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey], options: [], errorHandler: { (_, error) -> Bool in
print(error)
return false
}) {
var bytes = 0
for case let url as URL in enumerator {
bytes += url.fileSize ?? 0
}
return bytes
} else {
return nil
}
}
}
Usage
let fm = FileManager.default
let tmp = fm.temporaryDirectory
if let size = fm.directorySize(tmp) {
print(size)
}
What makes this barebones: doesn't precheck if a directory is a directory or a file is a file (returns nil
either way), and the results are returned in their native format (bytes as integers).