ios原生 swift文件计算文件的大小

25 阅读1分钟

在.swift文件里计算文件的大小

   // 计算文件大小
    var fileSize : UInt64 = 0
    do {
        let attr = try FileManager.default.attributesOfItem(atPath: newURL.path)
        fileSize = attr[FileAttributeKey.size] as! UInt64
        let dict = attr as NSDictionary
        fileSize = dict.fileSize()
    } catch {
        print("Error: \(error)")
    }
    var convertedValue: Double = Double(fileSize)
    var multiplyFactor = 0
    let tokens = ["bytes", "KB", "MB", "GB", "TB", "PB",  "EB",  "ZB", "YB"]
    while convertedValue > 1024 {
        convertedValue /= 1024
        multiplyFactor += 1
    }
    // 文件大小
    String(format: "%4.2f %@", convertedValue, tokens[multiplyFactor])