如何在 Swift 中使用 Alamofire 与 Multipart 一起使用具有不同键和多种参数的多个图像
Posted
技术标签:
【中文标题】如何在 Swift 中使用 Alamofire 与 Multipart 一起使用具有不同键和多种参数的多个图像【英文标题】:How to work with Multipart using Alamofire in Swift with multiple images with different keys and parameters with multiple kinds 【发布时间】:2019-09-03 11:10:34 【问题描述】:如果您正在处理具有不同键的多个图像并且还具有具有不同类型键值对的参数字典,例如“String”:“Any”,“String”:“[Any]”,如何快速处理多部分, [[String:Any]].
let headers: HTTPHeaders = ["Content-type": "multipart/form-data"]
Alamofire.upload(multipartFormData: (multipartFormData) in
for (key, value) in parameters
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
//Todo: - Images
var c = 0
for dictImage in arrImage
let validDict = kSharedInstance.getDictionary(dictImage)
for keyName in validDict.keys
print(keyName)
//Incr
c += 1
if let imageData = validDict[keyName] as? Data
multipartFormData.append(imageData, withName: "\(keyName)", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
, usingThreshold: UInt64(), to: urlString, method: .post, headers: headers) (result) in
switch result
case .success(let upload, _, _):
upload.responseJSON response in
print("Succesfully uploaded")
if((response.result.value) != nil)
debugPrint(response.result.value!)
let jsonData = JSON(response.result.value!)
if jsonData["status"].bool == true
completion(jsonData.dictionaryObject!, true)
else
completion(jsonData.dictionaryObject!, false)
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
failure(error, false)
【问题讨论】:
它只上传简单的(键,值)对。但是,无法上传图片和其余数据。 【参考方案1】:请检查以下代码。希望对你有帮助
Alamofire.upload(
multipartFormData: MultipartFormData in
for (key, value) in parameters
MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
for i in 0 ..< files.count
let fileName : String = "image\(i).jpg"
let datum : Data = files[i]
MultipartFormData.append(datum, withName: fileParamName, fileName: fileName, mimeType: "image/jpg")
, to: URLString, method: .post, headers: headers) (result) in
switch(result)
case .success(let upload, _, _):
upload.responseJSON response in
break;
case .failure(_):
【讨论】:
以上是关于如何在 Swift 中使用 Alamofire 与 Multipart 一起使用具有不同键和多种参数的多个图像的主要内容,如果未能解决你的问题,请参考以下文章
iOS swift Codable 不能与 Alamofire 一起使用 JSON 嵌套数据?
如何在 Swift / Alamofire 中使用 multipartFormData?