ios 在 Swift 中获取文件大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28268145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get file size in Swift
提问by Gralex
I tried several method to get file size, but always get zero.
我尝试了几种方法来获取文件大小,但总是得到零。
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)")
}
I get in log: File size = nil
我进入日志: File size = nil
回答by Duyen-Hoa
Use attributesOfItemAtPath
instead of attributesOfFileSystemForPath
+ call .fileSize() on your attr.
在您的属性上使用attributesOfItemAtPath
而不是attributesOfFileSystemForPath
+ 调用 .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();
}
In Swift 2.0, we use do try catch pattern, like this:
在 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)")
}
In Swift 3.x/4.0:
在 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)")
}
回答by gheclipse
Swift4: URL extension to easily access file attributes
Swift4:轻松访问文件属性的 URL 扩展
Extension:
延期:
extension URL {
var attributes: [FileAttributeKey : Any]? {
do {
return try FileManager.default.attributesOfItem(atPath: path)
} catch let error as NSError {
print("FileAttribute error: \(error)")
}
return nil
}
var fileSize: UInt64 {
return attributes?[.size] as? UInt64 ?? UInt64(0)
}
var fileSizeString: String {
return ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file)
}
var creationDate: Date? {
return attributes?[.creationDate] as? Date
}
}
Usage:
用法:
let fileUrl: URL
print("file size = \(fileUrl.fileSize), \(fileUrl.fileSizeString)")
回答by Jerome
SWIFT 3come from @Hoa's answer and plus a function let UInt64 to readable String.
SWIFT 3来自@Hoa 的回答,加上一个函数让 UInt64 变为可读字符串。
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])
}
回答by vadian
In Swift 3+ you can get the file size directly from the URL, (NS)FileManager
is not needed. And ByteCountFormatter
is a smart way to display the file size.
在 Swift 3+ 中,您可以直接从 URL 获取文件大小,(NS)FileManager
不需要。并且ByteCountFormatter
是一种显示文件大小的智能方式。
let url = Bundle.main.url(forResource:"movie", withExtension: "mov")!
do {
let resourceValues = try url.resourceValues(forKeys: [.fileSizeKey])
let fileSize = resourceValues.fileSize!
print("File size = " + ByteCountFormatter().string(fromByteCount: Int64(fileSize)))
} catch { print(error) }
Actually you can get the file size from the URL
even in Swift 2 but the syntax is a bit more cumbersome.
实际上,您可以从URL
Swift 2 中的even 中获取文件大小,但语法有点麻烦。
回答by Guy Brooker
Here is the answer from Biodave, with the correct file manager call
这是 Biodave 的答案,正确的文件管理器调用
func sizeForLocalFilePath(filePath:String) -> UInt64 {
do {
let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath)
if let fileSize = fileAttributes[NSFileSize] {
return (fileSize as! NSNumber).unsignedLongLongValue
} 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
}
For Swift 4.2:
对于 Swift 4.2:
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
}
回答by Ahmed Lotfy
Swift 4 solution: This function return MB size.
Swift 4 解决方案:此函数返回 MB 大小。
func sizePerMB(url: URL?) -> Double {
guard let filePath = url?.path else {
return 0.0
}
do {
let attribute = try FileManager.default.attributesOfItem(atPath: filePath)
if let size = attribute[FileAttributeKey.size] as? NSNumber {
return size.doubleValue / 1000000.0
}
} catch {
print("Error: \(error)")
}
return 0.0
}
回答by abdullahselek
Here is another two different implementation with Swift 4, one is formatted in details and other one is formatted by decimal.
这是Swift 4 的另外两种不同的实现,一种是详细格式,另一种是十进制格式。
The one with NumberFomatter
:
一个NumberFomatter
:
func fileSize(fromPath path: String) -> String? {
var size: Any?
do {
size = try FileManager.default.attributesOfItem(atPath: path)[FileAttributeKey.size]
} catch (let error) {
print("File size error: \(error)")
return nil
}
guard let fileSize = size as? UInt64 else {
return nil
}
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.formatterBehavior = .behavior10_4
return formatter.string(from: NSNumber(value: fileSize))
}
And the other one is defining with size units:
另一个是用尺寸单位定义:
func fileSize(fromPath path: String) -> String? {
guard let size = try? FileManager.default.attributesOfItem(atPath: path)[FileAttributeKey.size],
let fileSize = size as? UInt64 else {
return nil
}
// bytes
if fileSize < 1023 {
return String(format: "%lu bytes", CUnsignedLong(fileSize))
}
// KB
var floatSize = Float(fileSize / 1024)
if floatSize < 1023 {
return String(format: "%.1f KB", floatSize)
}
// MB
floatSize = floatSize / 1024
if floatSize < 1023 {
return String(format: "%.1f MB", floatSize)
}
// GB
floatSize = floatSize / 1024
return String(format: "%.1f GB", floatSize)
}
回答by Programer_saeed
Try This.
尝试这个。
let MyUrl = NSURL(fileURLWithPath: "*** Custom File Path ***")
let fileAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(MyUrl.path!)
let fileSizeNumber = fileAttributes[NSFileSize] as! NSNumber
let fileSize = fileSizeNumber.longLongValue
var sizeMB = Double(fileSize / 1024)
sizeMB = Double(sizeMB / 1024)
print(String(format: "%.2f", sizeMB) + " MB")
回答by boherna
URL extension in Swift to get the file size, if any.
Swift 中的 URL 扩展以获取文件大小(如果有)。
public extension URL {
var fileSize: Int? {
let value = try? resourceValues(forKeys: [.fileSizeKey])
return value?.fileSize
}
}
The reason for returning an optional Int is because an unknown file size cannot be considered as having a zero size.
返回可选 Int 的原因是因为未知文件大小不能被视为具有零大小。
回答by Jonny
Inspiration from a few other answers.
灵感来自其他一些答案。
extension URL {
var filesize: Int? {
let set = Set.init([URLResourceKey.fileSizeKey])
var filesize: Int?
do {
let values = try self.resourceValues(forKeys: set)
if let theFileSize = values.fileSize {
filesize = theFileSize
}
}
catch {
print("Error: \(error)")
}
return filesize
}
var filesizeNicelyformatted: String? {
guard let fileSize = self.filesize else {
return nil
}
return ByteCountFormatter.init().string(fromByteCount: Int64(fileSize))
}
}