3

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 ?

pkamb
  • 33,281
  • 23
  • 160
  • 191
Nawin P.
  • 223
  • 1
  • 4
  • 11

1 Answers1

3

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)")
}
jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • Oh! awesome, Thank you for your help @jnpdx. Can I ask more one question? for UIDocumentViewController, I have request any permission or open any capability ? – Nawin P. May 03 '21 at 18:22
  • @NawinP. I'm pretty sure, no. – aheze May 03 '21 at 18:22
  • Doesn't seem to work, probably is better to just count the content size. Error Domain=NSCocoaErrorDomain Code=257 "The file “....” couldn’t be opened because you don’t have permission to view it." – Cristi Băluță Sep 12 '22 at 08:58
  • @CristiBăluță sounds like in your case you have to access it via a security scoped resource. – jnpdx Sep 12 '22 at 13:51
  • @jnpdx I thought that is for macos and you need to choose the file with NSOpenPanel. If I pass the url to open it with UIDocument works just fine though, so I found the size from the count of the data. – Cristi Băluță Sep 14 '22 at 09:44
  • You are mistaken — it’s not just for macOS. – jnpdx Sep 14 '22 at 13:56