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"
相关推荐
请叫我飞哥@1 小时前
获取 Apple 授权登录的 Token
ios·swiftui·swift
HarderCoder3 小时前
Swift 6.2 默认把代码全扔 Main Actor,到底香不香?
swift
尽兴-4 小时前
macOS 系统下 Chrome 浏览器安装 HTTPS 证书完整指南
chrome·macos·https·证书·ssl·pem·crt
专注于大数据技术栈4 小时前
Mac本地安装python
macos
珊珊而川4 小时前
MAC-SQL:SQL-Llama 的具体训练流程
sql·macos·llama
孚亭14 小时前
Swift添加字体到项目中
开发语言·ios·swift
YGGP14 小时前
【Swift】LeetCode 76. 最小覆盖子串
swift
2501_9151063217 小时前
App 怎么上架 iOS?从准备资料到开心上架(Appuploader)免 Mac 上传的完整实战流程指南
android·macos·ios·小程序·uni-app·iphone·webview
青木狐17 小时前
关闭 macOS 屏幕捕捉 在录制或截图时显示的「录制指示浮窗」。
macos·mac
taokexia1 天前
SwiftUI 组件开发: 自定义下拉刷新和加载更多(iOS 15 兼容)
ios·swift