Getting file size using NSFileManager

I need to get the size of a video file using NSFileManager. I can get the url of my file. I found Objective-C code that seems to work, but my project is developed with Swift. How do I write the following code using 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];

      

+3


source to share


3 answers


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

      

+8


source


For SWIFT 2 try:



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
}

      

+9


source


For SWIFT 3 try:

    let fileSize = try! FileManager.default.attributesOfItem(atPath: "/bin/bash")[FileAttributeKey.size] as! Int

      

or even better:

let fileSize = (try! FileManager.default.attributesOfItem(atPath: "/bin/bash")[FileAttributeKey.size] as! NSNumber).uint64Value

      

0


source







All Articles