4

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];

3 Answers 3

10

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
Sign up to request clarification or add additional context in comments.

1 Comment

Btw, with Swift 2.1, error handling is different: do { let fileAttributes = try self.fileManager.attributesOfItemAtPath(logFilePathURL.path!) let fileSizeNumber = fileAttributes[NSFileSize] as! NSNumber let fileSize = fileSizeNumber.longLongValue } catch _ as NSError {}
9

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
}

Comments

1

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

1 Comment

In our app, we used to cast the NSFileSize attribute to UInt64. It worked perfectly on our development machines and on out test devices. However, it did NOT work on our build server, which ran the exact same XCode setup. There, we had to cast the attribute to an NSNumber, then get its uint64 property.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.