ios - 如何使用 swift 4 从数据中使用 Alamofire 多部分发送参数数组
问题描述
我Alamofire
用于将图像和文件上传到服务器。但是我在发送带有图像的参数数组时遇到问题。但是当我在 params 中发送一个数组时,它会将数组转换为JSON
字符串。但我想在参数中发送一个数组,而不是在JSON
字符串中。我进行了很多搜索,但没有得到任何解决方案。这是下面的代码。
let params = ["id":"101","arrayParam":["1232","12344","14325"]]
let url = www.khxjjhdfsj.com/hsdgs
let headers: HTTPHeaders = [
/* "Authorization": "your_access_token", in case you need authorization header */
"Content-type": "multipart/form-data"
]
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in params
{
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
if let data = imageData
{
multipartFormData.append(data, withName: "file", fileName: fileName, mimeType: "image/png")
}
if let data = pdfData
{
multipartFormData.append(data, withName: "file", fileName: fileName, mimeType:"application/pdf")
}
}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded")
if let err = response.error
{
onError?(err)
return
}
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
onError?(error)
}
}
解决方案
let params = [
"key":value,
"key1": key2] as [String : Any]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 30000
manager.request(url, method: .post, parameters: params)
.responseJSON {
response in
switch response.result {
case .success:
stopActivityIndicator()
print(response)
if let result = response.result.value {
let JSON = result as! NSDictionary
print(JSON)
let ResponseSuccess = JSON.object(forKey: "response")!
self.displayAlert(Message: ResponseSuccess as! String, myView:self)
}
case .failure( _):
if let result = response.result.value {
stopActivityIndicator()
let JSON = result as! NSDictionary
print(JSON)
let ResponseFail = JSON.object(forKey: "response")!
self.displayAlert(Message: ResponseFail as! String, myView:self)
}
}
}
推荐阅读
- multithreading - 为什么外键 + 主键的这种组合会产生 Postgres 死锁?
- javascript - 如何从谷歌应用脚本中的 JSON 数组获取数据?
- javascript - _valueable 名称(下划线 + 有价值的名称) javascript
- android - Android阻止滚动视图滚动到videoView
- ruby-on-rails - mac上用于rails的Docker容器非常慢
- php - 为什么 Laravel b64-encode 加密数据?
- python - 使用 python 连接到 OpenVPN 配置
- java - 如何使这个程序在 Java 的末尾显示正确的值?
- react-native - React Native Expo 视频 av-expo
- generics - Kotlin:传递 Gson 使用的类型