Swift 3 Alamofire multipart upload

左心房为你撑大大i 提交于 2019-11-28 18:09:12

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)
Mitul Marsoniya

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
}

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!