Alamofire 4 多部分
Posted
技术标签:
【中文标题】Alamofire 4 多部分【英文标题】:Alamofire 4 multipart 【发布时间】:2016-11-29 13:34:52 【问题描述】:我尝试使用 Alamofire 4 创建多部分请求。 我不会添加 [String: AnyObject] 作为一部分。但是,当我的有效载荷 dict 应用程序中的 multipartFormData 附加 bool 或 [Int] 崩溃时!我的错在哪里?
let payload: [String: AnyObject] = [
"key1": "val1" as AnyObject,
"key2": true as AnyObject,
"key3" : [1,2,3,4] as AnyObject
]
let requestString = "http://www.url.com/api/action"
Alamofire.upload(multipartFormData: (multipartFormData) in
for (key, value) in payload
multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)!, withName: "request", fileName: key, mimeType: "application/json")
multipartFormData.append(imageUrl, withName: "fileData", fileName: "image", mimeType: "image/png")
, to: requestString, method: .post , headers: ["Content-Type": "multipart/form-data"], encodingCompletion: (result) in
switch result
case .success(let upload, _, _):
upload.uploadProgress(closure: (progress) in
print(progress.fractionCompleted * 100)
)
upload.responseJSON(completionHandler: (response) in
)
case .failure(let error):
print(error)
)
【问题讨论】:
【参考方案1】:您发送了错误的参数。试试下面的 Alamofire 4 代码。
let payload: [String: AnyObject] = [
"key1": "val1" as AnyObject,
"key2": true as AnyObject,
"key3" : [1,2,3,4] as AnyObject
]
let requestString = "http://www.url.com/api/action"
Alamofire.upload(multipartFormData: (multipartFormData) in
multipartFormData.append(UIImageJPEGRepresentation(self.photoImageView.image!, 0.5)!, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
for (key, value) in payload
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
, to: requestString, method: .post , headers:nil, encodingCompletion: (result) in
switch result
case .success(let upload, _, _):
upload.uploadProgress(closure: (progress) in
print(progress.fractionCompleted * 100)
)
upload.responseJSON(completionHandler: (response) in
)
case .failure(let error):
print(error)
)
【讨论】:
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
不适用于数组,例如"key3" : [1,2,3,4] as AnyObject
以上是关于Alamofire 4 多部分的主要内容,如果未能解决你的问题,请参考以下文章