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

时间:2018-03-25 19:35:32

标签: ios swift alamofire multipart uidocumentpickerviewcontroller

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?

1 个答案:

答案 0 :(得分:1)

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.