macos – 如何在OS X上使用Swift获取目录大小

我试图获得一个目录的大小,以及它使用Swift在OS X上的内容.到目前为止,我只能获得目录本身的大小,而不是它的内容.对于我的大多数目录,它通常显示6,148字节的值,但它确实有变化.

我已经尝试过下面文件中的directorySize()函数,但它也返回了6,148个字节.

https://github.com/amosavian/ExtDownloader/blob/2f7dba2ec1edd07282725ff47080e5e7af7dabea/Utility.swift

我尝试了这个问题的前两个答案,但不确定它需要什么参数将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
// 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"
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...