我试图获得一个目录的大小,以及它使用Swift在OS X上的内容.到目前为止,我只能获得目录本身的大小,而不是它的内容.对于我的大多数目录,它通常显示6,148字节的值,但它确实有变化.
我已经尝试过下面文件中的directorySize()函数,但它也返回了6,148个字节.
我尝试了这个问题的前两个答案,但不确定它需要什么参数将Swift传递给Objective-C函数.我相信它想要一个指针(我是学习的初级程序员).
Calculate the size of a folder
而且我无法从这里得到Swift的答案也可以用于我的目的.
How to get the file size given a path?
我正在使用Xcode 7.0并运行OS X 10.10.5.
更新:Xcode 8.2.1•Swift 3.0.2
原文链接:https://www.f2er.com/swift/320033.html// 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 bytes" }