如何在Alamofire中发布这种形式的参数?
[{"view_id":"108","Class_id":"VIII"}]
正如通常Alamofire
接受[String:Any]
参数,当我在Alamofire
请求中输入此参数时,它会引发错误:
"extra call method"
你说As normally Alamofire accept [String:Any] parameters
,然后你通过[[String: Any]]
。
尝试在http Body中传递您的数据。
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
}