【发布时间】:2018-10-12 09:09:05
【问题描述】:
如何在 Alamofire 中发布这种形式的参数?
[{"view_id":"108","Class_id":"VIII"}]
像往常一样Alamofire 接受 [String:Any] 参数,当我在Alamofire 请求中输入此参数时,它会引发错误:
"extra call method"
【问题讨论】:
标签: ios iphone swift alamofire
如何在 Alamofire 中发布这种形式的参数?
[{"view_id":"108","Class_id":"VIII"}]
像往常一样Alamofire 接受 [String:Any] 参数,当我在Alamofire 请求中输入此参数时,它会引发错误:
"extra call method"
【问题讨论】:
标签: ios iphone swift alamofire
你说As normally Alamofire accept [String:Any] parameters,然后你传递了[[String: Any]]。
尝试在 hhtpBody 中传递您的数据。
let urlString = "yourString"
guard let url = URL(string: urlString) else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
do {
request.httpBody = try JSONSerialization.data(withJSONObject: your_parameter_aaray)
} catch let error {
print("Error : \(error.localizedDescription)")
}
Alamofire.request(request).responseJSON{ (response) in
}
【讨论】:
您可以使用自定义编码来发送请求中的参数。检查Alamofire docs on custom-encoding
struct JSONStringArrayEncoding: ParameterEncoding {
private let jsonArray: [[String: String]]
init(jsonArray: [[String: String]]) {
self.jsonArray = jsonArray
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
let data = try JSONSerialization.data(withJSONObject: jsonArray, options: [])
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
return urlRequest
}
}
使用方法:
Alamofire.request("https://myserver.com/api/path", method: .post, encoding: JSONStringArrayEncoding).responseJSON { response in
}
【讨论】:
试试这个方法来解决:
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: header).validate(statusCode: 200..<300) .responseJSON { response in
}
【讨论】: