Swift 3 Alamofire multipart upload

Solution 1:

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)

Solution 2:

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
}

Solution 3:

In swift 3, trying to set multipartFormData as @DCDC pointed out in his solution. XCode try to cast to AnyObject before .data(), so instead of

value.data(using: String.Encoding.utf8)!, withName: key

I did

[replace_your_var_name_here].data(using: String.Encoding.utf8)!, withName: key

In my case my var list was not big so hardcoding was an option.

Solution 4:

For Swift 3 and Alamofire ~4.3.0

If someone like me tried to get request object synchronously (without using locks or dispatch_groups) you can use this approach:

// outer function
...
let string = "string to send"
let multipartFormData = MultipartFormData()
multipartFormData.append(string.data(using: .utf8)!, withName: "str")

guard let data = try? multipartFormData.encode() else {
    // fail appropriately
}

let request = sessionManager.upload(data,
                                    to: url,
                                    method: .post,
/* this is VERY IMPORTANT LINE */   headers: ["Content-Type" : multipartFormData.contentType])

request.validate()
// do whatever you need with request

Please note that you need to set Content-Type header from you multipartFormData as it contains boundaries.

If you don't need to have your request object synchronously the other answer with

Alamofire.upload(multipartFormData: { (multipartFormData) in

is working as expected. In case of successful encoding of data it will return you request object in callback closure.

IMPORTANT NOTE: if you use the method I have described, it will block your thread (in most cases you probably are in Main thread) to copy and encode your data. So don't use it for large files or whatever. It is async in Alamofire on purpose.