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"
相关推荐
Magnetic_h7 小时前
【iOS】方法与消息底层分析
笔记·学习·macos·ios·objective-c·cocoa
xchenhao7 小时前
基于 Flutter 的开源文本 TTS 朗读器(支持 Windows/macOS/Android)
android·windows·flutter·macos·openai·tts·朗读器
IT WorryFree11 小时前
macos安装iper3
网络·macos·iperf·打流
pk_xz12345617 小时前
在Intel Mac的PyCharm中设置‘add bin folder to the path‘的解决方案
ide·人工智能·科技·算法·macos·pycharm·机器人
Fine姐1 天前
传感器WSNs TheDataLinkLayer——X-MAC
macos
瓜子三百克2 天前
值类型大小与内存分配
swift·内存分配
初级代码游戏2 天前
Maui劝退:用windows直接真机调试iOS,无须和Mac配对
macos·ios·配置·maui·热重载
草巾冒小子2 天前
Mac如何连接惠普M126a打印机(教程篇)
macos
蒙小萌19933 天前
苹果UI 设计
macos·ui·cocoa
用户49055816081253 天前
Homebrew 简介
macos