DCDC DCDC - 2 months ago 646
Swift Question

Swift 3 Alamofire multipart upload

Thanks to migration to Swift 3, I find it difficult to compile my project that uses Alamofire.

The problem occurs when uploading multipartFormData:

Alamofire.upload(.POST, URL, headers: headers, multipartFormData: {
multipartFormData in
.
.
.
})



Ambiguous reference to member 'upload(_:to:method:headers:)'


Any help much appreciated, thanks in advance!

RESOLVED:

Alamofire.upload(multipartFormData: { (multipartFormData) in

multipartFormData.append(fileData, withName: "file_pack", fileName: "file_pack", mimeType: "text/plain")


for (key, value) in self.parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, with: URL2, encodingCompletion: { (result) in

switch result {
case .success(let upload, _, _):

upload.responseJSON { response in
self.delegate?.showSuccessAlert()
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
// self.showSuccesAlert()
self.removeImage("frame", fileExtension: "txt")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}

case .failure(let encodingError):
self.delegate?.showFailAlert()
print(encodingError)
}

})


This is how upload method should be implemented in Swift 3

Answer

For example, using Alamofire 4.0.0 in Swift 3:

(make sure you are 4.0.0 ready as it looks like you haven't updated your Alamofire yet)

Alamofire.upload(multipartFormData: { (multipartFormData) in
        // code
    }, to: URL, encodingCompletion: { (result) in
        // code
    })

or

Alamofire.upload(multipartFormData: { (multipartFormData) in
        // code
    }, with: URL, encodingCompletion: { (result) in
        // code
    })

So headers need to be passed by URL request:

let URL = try! URLRequest(url: "http://example.com", method: .get, headers: headers)