Swift 获取文件大小

2019-12-02  本文已影响0人  WMSmile

最近在项目里面,有做的获取文件大小的功能。所以就在在这儿分享一下。

swift3.0

func sizeForLocalFilePath(filePath:String) -> UInt64 {
    do {
        let fileAttributes = try FileManager.default.attributesOfItem(atPath: filePath)
        if let fileSize = fileAttributes[FileAttributeKey.size]  {
            return (fileSize as! NSNumber).uint64Value
        } else {
            print("Failed to get a size attribute from path: \(filePath)")
        }
    } catch {
        print("Failed to get file attributes for local path: \(filePath) with error: \(error)")
    }
    return 0
}
func covertToFileString(with size: UInt64) -> String {
    var convertedValue: Double = Double(size)
    var multiplyFactor = 0
    let tokens = ["bytes", "KB", "MB", "GB", "TB", "PB",  "EB",  "ZB", "YB"]
    while convertedValue > 1024 {
        convertedValue /= 1024
        multiplyFactor += 1
    }
    return String(format: "%4.2f %@", convertedValue, tokens[multiplyFactor])
}

参考文章get-file-size-in-swift

另外一种获取方法 通过data的大小转换成size

swift 4.0

/// get file size
///
/// - Parameter url: url
/// - Returns: Double file size
class func wm_getFileSize(_ url:String) -> Double {
    if let fileData:Data = try? Data.init(contentsOf: URL.init(fileURLWithPath: url)) {
        let size = Double(fileData.count) / (1024.00 * 1024.00)
        return size
    }
    return 0.00
}
上一篇下一篇

猜你喜欢

热点阅读