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.
You can call . fileSize() on attr to get file size.
unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize]; This returns the file size in Bytes. I like this one.
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)") } 
                        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 } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With