How to get file name and file size from UIDocumentPickerViewController in iOS 14?

2.2k views Asked by At

I have to create feature for upload some document in pdf type and have to show name and file size with file that I selected from UIDocumentPickerViewController 's delegate before upload it.

How can I get its name and file size ?

1

There are 1 answers

6
jnpdx On BEST ANSWER

In your UIDocumentPickerDelegate, you have will end up implementing documentPicker(_:didPickDocumentsAt:), which will give you an array of URLs. You can get the name of a file using url.lastPathComponent.

Regarding the file size, once you have the same URL from above, you can query the file size (may solutions listed here: Swift - Get file size from url):

do {
  let attribute = try FileManager.default.attributesOfItem(atPath: url.path)
  if let size = attribute[FileAttributeKey.size] as? NSNumber {
    let sizeInMB = size.doubleValue / 1000000.0
  }
} catch {
  print("Error: \(error)")
}