2

I'm trying to get the selected filename with extension from UIDocumentPickerViewController but the filename has "]" at the end of the file extension. Any suggestion on what is the correct way?

Here is my code:

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    let filename = URL(fileURLWithPath: String(describing:urls)).lastPathComponent // print: myfile.pdf]
    self.pickedFile.append(filename)
    // display picked file in a view
    self.dismiss(animated: true, completion: nil)
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Kuru
  • 23
  • 1
  • 5

2 Answers2

9

Never use String(describing:) for anything other than debug output. Your code is generating debug output of an array of URL instances. That output will be something like:

[file:///some/directory/someFileA.ext,file:///some/directory/otherFile.ext]

Of course the array output will contain however many files were selected.

You then attempt to create a file URL from that debug output of the array of URL instances and then get the last path component of that. This is why you get the trailing ].

Just access the element from the array that you want. Don't create a new URL.

if let filename = urls.first?.lastPathComponent {
    self.pickedFile.append(filename)
}

Better yet, add them all:

for url in urls {
    self.pickedFile.append(url.lastPathComponent)
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
2

urls is URL array, not URL, not String

try:

 func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    if let filename =  urls.first?.lastPathComponent {
        self.pickedFile.append(filename)
        // display picked file in a view
        self.dismiss(animated: true, completion: nil)
    }
}
Nguyen Hoan
  • 1,583
  • 1
  • 11
  • 18