Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Swift) How can I get a Data representation of the documentPicker URL

I use the didPickDocumentAt function to retrieve the url of the picked file in the DocumentPickerViewController. I have a multipart upload function that uses alamofire to upload files to the backend.

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
    print(url)
    uploadMultipartFile()
}

My question is: How can I get a data representation of the file I have picked so I can pass it to my uploadMultipartFile function?

The Files can be pdf, .docx, or any kind of file. What is the approach?

like image 595
Jochen Österreicher Avatar asked Oct 24 '25 18:10

Jochen Österreicher


1 Answers

Have a look at dataWithContentsOfURL:

Returns a data object containing the data from the location specified by a given URL.

Note that it throws if it cannot create the data representation from the URL.

So in your case maybe something like this:

func documentPicker(_ controller: UIDocumentPickerViewController, 
      didPickDocumentsAt urls: [URL]) {
print(url)
    do {
        var documentData = [Data]()
        for url in urls {
            documentData.append(try Data(contentsOf: url))
        }

        //hopefully you have an array of data elements now :)                
        uploadMultipartFile()
    } catch {
        print("no data")
    }
}

Hope that helps.

like image 155
pbodsk Avatar answered Oct 26 '25 07:10

pbodsk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!