Search code examples
iosswiftalamofiremultipartuidocumentpickerviewcontroller

(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?


Solution

  • 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.