You can use the FileManager
class in Swift to determine the size of a directory:
func calculateDirectorySize(at url: URL) -> Int64 {
let fileManager = FileManager.default
var folderSize: Int64 = 0
guard fileManager.fileExists(atPath: url.path) else { return folderSize }
do {
let files = try fileManager.contentsOfDirectory(atPath: url.path)
for file in files {
let path = url.appendingPathComponent(file).path
let attributes = try fileManager.attributesOfItem(atPath: path)
folderSize += attributes[FileAttributeKey.size] as! Int64
}
} catch {
print("Error while enumerating files \(url.path): \(error.localizedDescription)")
}
return folderSize
}
You can call this function with the URL of the directory you want to determine the size of:
let directoryURL = URL(fileURLWithPath: "/Users/Username/Documents/")
let size = calculateDirectorySize(at: directoryURL)
print("Directory size: \(size)")
This function will calculate the total size of all the files within the directory, including any subdirectories.
Asked: 2022-07-28 11:00:00 +0000
Seen: 18 times
Last updated: Nov 07 '22