Kuru
Kuru

Reputation: 23

How to get correct filename from UIDocumentPicker, didPickDocumentsAt urls: [URL]

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)
}

Upvotes: 2

Views: 5041

Answers (2)

rmaddy
rmaddy

Reputation: 318854

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)
}

Upvotes: 9

Nguyen Hoan
Nguyen Hoan

Reputation: 1693

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)
    }
}

Upvotes: 2

Related Questions