Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Get file size from url

i am using documentPicker to get url path of any document and then uploaded to the database. I am choosing file (pdf, txt ..) , the upload is working but i want to limit the size of the file .

 public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {          self.file = url //url         self.path = String(describing: self.file!) // url to string         self.upload = true //set upload to true         self.attachBtn.setImage(UIImage(named: "attachFilled"), for: .normal)//set image         self.attachBtn.tintColor = UIColor.black //set color tint         sendbtn.tintColor = UIColor.white //           do         {             let fileDictionary = try FileManager.default.attributesOfItem(atPath: self.path!)             let fileSize = fileDictionary[FileAttributeKey.size]             print ("\(fileSize)")         }          catch{             print("Error: \(error)")         }      } 

I get the error message , this file does not exist , where does the document picker save the file and how to get his attributes.

like image 781
yasser h Avatar asked May 05 '17 05:05

yasser h


People also ask

How do I check the size of a file in Swift?

You can call . fileSize() on attr to get file size.

How do I get the size of a file in Objective C?

unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize]; This returns the file size in Bytes. I like this one.


2 Answers

First of all, in the file system you get the path of a URL with the path property.

self.path = url.path 

But you don't need that at all. You can retrieve the file size from the URL directly:

self.path = String(describing: self.file!) // url to string

do {     let resources = try url.resourceValues(forKeys:[.fileSizeKey])     let fileSize = resources.fileSize!     print ("\(fileSize)") } catch {     print("Error: \(error)") } 
like image 102
vadian Avatar answered Sep 27 '22 21:09

vadian


Swift 4:

func sizePerMB(url: URL?) -> Double {     guard let filePath = url?.path else {         return 0.0     }     do {         let attribute = try FileManager.default.attributesOfItem(atPath: filePath)         if let size = attribute[FileAttributeKey.size] as? NSNumber {             return size.doubleValue / 1000000.0         }     } catch {         print("Error: \(error)")     }     return 0.0 } 
like image 35
Ahmed Lotfy Avatar answered Sep 27 '22 19:09

Ahmed Lotfy