我需要使用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];
答案 0 :(得分:9)
试试这段代码:
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
答案 1 :(得分:9)
对于SWIFT 2,请尝试:
DESCRIBE
答案 2 :(得分:1)
对于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