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
To anyone who is looking for a solution for Swift 5+ and Xcode 11+ look at this gist
func directorySize(url: URL) -> Int64 {
let contents: [URL]
do {
contents = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [.fileSizeKey, .isDirectoryKey])
} catch {
return 0
}
var size: Int64 = 0
for url in contents {
let isDirectoryResourceValue: URLResourceValues
do {
isDirectoryResourceValue = try url.resourceValues(forKeys: [.isDirectoryKey])
} catch {
continue
}
if isDirectoryResourceValue.isDirectory == true {
size += directorySize(url: url)
} else {
let fileSizeResourceValue: URLResourceValues
do {
fileSizeResourceValue = try url.resourceValues(forKeys: [.fileSizeKey])
} catch {
continue
}
size += Int64(fileSizeResourceValue.fileSize ?? 0)
}
}
return size
}