gpt4 book ai didi

ios - 在 Swift 中获取文件大小

转载 作者:行者123 更新时间:2023-11-30 13:36:33 25 4
gpt4 key购买 nike

我尝试了多种方法来获取文件大小,但总是为零。

let path = NSBundle.mainBundle().pathForResource("movie", ofType: "mov")
let attr = NSFileManager.defaultManager().attributesOfFileSystemForPath(path!, error: nil)
if let attr = attr {
let size: AnyObject? = attr[NSFileSize]
println("File size = \(size)")
}

我进入日志:文件大小= nil

最佳答案

使用attributesOfItemAtPath而不是attributesOfFileSystemForPath+ 在你的 attr 上调用 .fileSize()。

var filePath: NSString = "your path here"
var fileSize : UInt64
var attr:NSDictionary? = NSFileManager.defaultManager().attributesOfItemAtPath(filePath, error: nil)
if let _attr = attr {
fileSize = _attr.fileSize();
}

在 Swift 2.0 中,我们使用 do try catch 模式,如下所示:

let filePath = "your path here"
var fileSize : UInt64 = 0

do {
let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath)

if let _attr = attr {
fileSize = _attr.fileSize();
}
} catch {
print("Error: \(error)")
}

在 Swift 3.x/4.0 中:

let filePath = "your path here"
var fileSize : UInt64

do {
//return [FileAttributeKey : Any]
let attr = try FileManager.default.attributesOfItem(atPath: filePath)
fileSize = attr[FileAttributeKey.size] as! UInt64

//if you convert to NSDictionary, you can get file size old way as well.
let dict = attr as NSDictionary
fileSize = dict.fileSize()
} catch {
print("Error: \(error)")
}

关于ios - 在 Swift 中获取文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36004514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com