macos – 如何在OS X上使用Swift获取目录大小
发布时间:2020-12-14 05:45:28 所属栏目:百科 来源:网络整理
导读:我试图获得一个目录的大小,以及它使用Swift在OS X上的内容.到目前为止,我只能获得目录本身的大小,而不是它的内容.对于我的大多数目录,它通常显示6,148字节的值,但它确实有变化. 我已经尝试过下面文件中的directorySize()函数,但它也返回了6,148个字节. https
我试图获得一个目录的大小,以及它使用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" } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |