Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 848
theDC Avatar asked Sep 20 '16 10:09

theDC


2 Answers

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)
like image 72
pedrouan Avatar answered Nov 12 '22 14:11

pedrouan


Try this one and url set as @pedrouan said.

Alamofire.upload(multipartFormData: { (multipartFormData) in
       multipartFormData.append(imageData, withName: "xyz", fileName: "file.jpeg", mimeType: "image/jpeg")
}, to: url) 
{ (result) in
      //result
}
like image 7
Mitul Marsoniya Avatar answered Nov 12 '22 16:11

Mitul Marsoniya