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"
相关推荐
冯汉栩20 小时前
Swift Control DateSelection(日期选择框)
ios·cocoa·swift
守城小轩1 天前
Chromium 148 编译指南 macOS篇:环境配置要求(一)
macos
冯汉栩1 天前
Swift Control DashLineView(虚线)
开发语言·ios·swift
Codeking__1 天前
iOS 动画:core Animation 底层原理
macos·objective-c·cocoa
SatanII1 天前
读懂 SELinux:强制访问控制 MAC,解决 httpd 服务权限报错实战
linux·运维·服务器·网络·macos
2501_915918411 天前
iOS 真机调试工具推荐,安装运行、性能分析有哪些工具
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
mCell2 天前
谁在为 AI 开车:Agent 浏览器生态调研(2026)
chrome·macos·agent
东坡肘子2 天前
越来越慢的 App Review,拦住了谁? -- 肘子的 Swift 周报 #149
人工智能·swiftui·swift
sudebao点com2 天前
一次“Google 能打开,FlexTV 打不开”的 DNS 故障排查:从 curl 超时到完整证据链
windows·macos·https·cdn·dns·nslookup·网络排错
冯汉栩3 天前
Swift Control View,Label渐变颜色(源码)
开发语言·ios·swift