macOS 获取文件夹大小

macOS 获取文件夹大小

获取文件夹大小的扩展如下:

swift 复制代码
extension URL {
    var fileSize: Int? { // in bytes
        do {
            let val = try self.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey])
            return val.totalFileAllocatedSize ?? val.fileAllocatedSize
        } catch {
            print(error)
            return nil
        }
    }
}
extension FileManager {
    func folderSize(_ dir: URL) -> Int? {
        if let enumerator = self.enumerator(at: dir, includingPropertiesForKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey], options: [], errorHandler: { (_, error) -> Bool in
            print(error)
            return false
        }) {
            var bytes = 0
            for case let url as URL in enumerator {
                bytes += url.fileSize ?? 0
            }
            return bytes
        } else {
            return nil
        }
    }
}

但是返回来的是字节数,如果要转换成 MB 或者 GB,需要自己做转换,那再来扩展吧。

swift 复制代码
extension FileManager {
    func convertBytesToReadableUnit(_ bytes: Int64) -> String {
        let formatter = ByteCountFormatter()
        formatter.countStyle = .binary
        formatter.allowedUnits = [.useAll]
        formatter.includesUnit = true
        formatter.isAdaptive = true
        return formatter.string(fromByteCount: bytes)
    }
}

let bytes: Int64 = 123456789
let readableUnit = FileManager.default.convertBytesToReadableUnit(bytes)
print(readableUnit) // Output: "117.7 MB"
相关推荐
不二狗43 分钟前
每日算法 -【Swift 算法】电话号码字母组合
开发语言·算法·swift
tonngw6 小时前
【Mac 从 0 到 1 保姆级配置教程 16】- Docker 快速安装配置、常用命令以及实际项目演示
macos·docker·容器·开源·github·docker desktop·orbstack
ItisNagatoYuki15 小时前
Mac M芯片 RAG 极简流程 安装 ragflow + LM studio
macos
云攀登者-望正茂18 小时前
如何在mac上安装podman
macos·podman
HarderCoder20 小时前
ByAI:iOS 生命周期:AppDelegate 与 SceneDelegate 中的 `willEnterForeground` 方法解析
swift
大熊猫侯佩21 小时前
SwiftData 如何在 Widgets 和 App 的界面之间同步数据变化?
swiftui·swift·apple watch
YungFan21 小时前
SwiftUI-Preference
swiftui·swift
HarderCoder21 小时前
ByAI:使用DRY原则编写干净可复用的Swift代码
swift
season_zhu1 天前
Swift:优雅又强大的语法糖——Then库
ios·架构·swift