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"
相关推荐
denggun1234527 分钟前
ios-WebP
macos·php·cocoa
Digitally1 小时前
解决 iPhone 和 Mac 之间备忘录无法同步的9种方法
macos·ios·iphone
小妖同学学AI2 小时前
Mac远程控制新篇章:UU远程被控端深度测评
macos·远程控制·uu
胎粉仔2 小时前
Swift 初阶 —— Sendable 协议 & data races
开发语言·ios·swift·sendable·并发域·data races
xiaaaa.z2 小时前
macos HbuildX 使用cli脚本创建uniapp 运行时报错“cli项目运行依赖本地的Nodejs环境,请先安装并配置到系统环境变量后重试。”
macos·uni-app
m0_495562783 小时前
Swift-Enum
java·算法·swift
m0_495562783 小时前
Swift-snapKit使用
开发语言·elasticsearch·swift
不惑_4 小时前
[特殊字符] 在 macOS 上设置 SQLite
数据库·macos·sqlite
2501_927541094 小时前
Mac多功能音视频AI处理工具VideoProc Converter AI
macos·音视频
denggun123454 小时前
ios-AVIF
macos·ios·cocoa