更新:的Xcode 8.2.1•斯威夫特3.0.2
// get your directory url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// check if the url is a directory
if (try? documentsDirectoryURL.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true {
print("url is a folder url")
// lets get the folder files
var folderSize = 0
(try? FileManager.default.contentsOfDirectory(at: documentsDirectoryURL, includingPropertiesForKeys: nil))?.lazy.forEach {
folderSize += (try? $0.resourceValues(forKeys: [.totalFileAllocatedSizeKey]))?.totalFileAllocatedSize ?? 0
}
// format it using NSByteCountFormatter to display it properly
let byteCountFormatter = ByteCountFormatter()
byteCountFormatter.allowedUnits = .useBytes
byteCountFormatter.countStyle = .file
let folderSizeToDisplay = byteCountFormatter.string(for: folderSize) ?? ""
print(folderSizeToDisplay) // "X,XXX,XXX bytes"
}
如果你想包括您需要使用enumeratorAtURL如下所有子文件夾,隱藏文件和文件包的後裔:
// get your directory url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// check if the url is a directory
if (try? documentsDirectoryURL.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true {
var folderSize = 0
(FileManager.default.enumerator(at: documentsDirectoryURL, includingPropertiesForKeys: nil)?.allObjects as? [URL])?.lazy.forEach {
folderSize += (try? $0.resourceValues(forKeys: [.totalFileAllocatedSizeKey]))?.totalFileAllocatedSize ?? 0
}
let byteCountFormatter = ByteCountFormatter()
byteCountFormatter.allowedUnits = .useBytes
byteCountFormatter.countStyle = .file
let sizeToDisplay = byteCountFormatter.string(for: folderSize) ?? ""
print(sizeToDisplay) // "X,XXX,XXX bytes"
}
有低於2個的屏幕截圖。我無法獲得大小匹配。 My Documents目錄是〜1.50綠帶 https://drive.google.com/file/d/0B8F7IPsTUK7gUEVzeU5JRTF0Qms/view?usp=sharing 但控制檯只報告272個字節 https://drive.google。 com/file/d/0B8F7IPsTUK7gaDBiZkdfREZhWkE/view?usp = sharing – JackVaughn
它是本地文件夾嗎? –
就是這樣。對我的代碼進行的唯一更改是打印文檔url,以確保它是正確的。 – JackVaughn