使用 NSFileManager 获取文件大小
Getting file size with NSFileManager
我需要使用 NSFileManager 获取视频文件的大小。我可以检索文件的 URL 路径。我发现 Objective-C 代码似乎有效,但我的项目是使用 Swift 开发的。如何使用 Swift?
编写以下代码
NSURL *videoUrl=(NSURL*)[info objectForKey:UIImagePickerControllerMediaURL];
//Error Container
NSError *attributesError;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[videoUrl path] error:&attributesError];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];
试试这个代码:
let videoUrl = info[UIImagePickerControllerMediaURL] as! NSURL
var attributesError: NSError?
let fileAttributes = NSFileManager.defaultManager().attributesOfItemAtPath(videoURL.path!, error: &attributesError)!
let fileSizeNumber = fileAttributes[NSFileSize] as! NSNumber
let fileSize = fileSizeNumber.longlongValue
对于SWIFT 2 次尝试:
let videoUrl = info[UIImagePickerControllerMediaURL] as! NSURL
do{
let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(videoURL.path!)
let fileSize = fileAttributes[NSFileSize]
}
catch let err as NSError{
//error handling
}
对于SWIFT 3 次尝试:
let fileSize = try! FileManager.default.attributesOfItem(atPath: "/bin/bash")[FileAttributeKey.size] as! Int
甚至更好:
let fileSize = (try! FileManager.default.attributesOfItem(atPath: "/bin/bash")[FileAttributeKey.size] as! NSNumber).uint64Value
我需要使用 NSFileManager 获取视频文件的大小。我可以检索文件的 URL 路径。我发现 Objective-C 代码似乎有效,但我的项目是使用 Swift 开发的。如何使用 Swift?
编写以下代码NSURL *videoUrl=(NSURL*)[info objectForKey:UIImagePickerControllerMediaURL];
//Error Container
NSError *attributesError;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[videoUrl path] error:&attributesError];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];
试试这个代码:
let videoUrl = info[UIImagePickerControllerMediaURL] as! NSURL
var attributesError: NSError?
let fileAttributes = NSFileManager.defaultManager().attributesOfItemAtPath(videoURL.path!, error: &attributesError)!
let fileSizeNumber = fileAttributes[NSFileSize] as! NSNumber
let fileSize = fileSizeNumber.longlongValue
对于SWIFT 2 次尝试:
let videoUrl = info[UIImagePickerControllerMediaURL] as! NSURL
do{
let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(videoURL.path!)
let fileSize = fileAttributes[NSFileSize]
}
catch let err as NSError{
//error handling
}
对于SWIFT 3 次尝试:
let fileSize = try! FileManager.default.attributesOfItem(atPath: "/bin/bash")[FileAttributeKey.size] as! Int
甚至更好:
let fileSize = (try! FileManager.default.attributesOfItem(atPath: "/bin/bash")[FileAttributeKey.size] as! NSNumber).uint64Value