user1951145 user1951145 - 1 year ago 139
iOS Question

Getting file size with NSFileManager

I need to get size of video file with NSFileManager. I can retrieve URL path of my file. I found Objective-C code which seems working but my project is developed with Swift. How can I write the following code with 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];

Answer Source

Try this code:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download