我通过 Alamofire 发送 JSON 请求,但是该函数发送 nil。尽管我已经验证所有项目都按其应有的方式工作。
辅助功能:
func requestServer(_ method: HTTPMethod,_ path: String,_ body: [String : Any]?,_ encoding: ParameterEncoding,_ headers: [String : Any]?,_ completionHandler: @escaping (JSON) -> Void){
let url = baseURL?.appendingPathComponent(path)
refreshTokenIfNeed {
Alamofire.request(url!, method: method, parameters: body, encoding: encoding, headers: nil).responseJSON{ (response) in
switch response.result {
case .success(let value):
let jsonData = JSON(value)
completionHandler(jsonData)
break
case .failure:
completionHandler(nil)
break
}
}
}
}
发送Nil的函数:
func pickOrder(orderId: Int, completionHandler: @escaping (JSON) -> Void) {
let path = "api/driver/order/pick/"
let header: [String: Any] = ["Authorization": "Bearer " + self.accessToken]
let body: [String: Any] = [
"order_id":"\(orderId)"
]
print("header", header, "body", body)
requestServer(.post, path, body, URLEncoding(), header, completionHandler)
}
任何见解都会有所帮助!
在方法中传递
JSONEncoding.default
以发送给定的 JSON:
requestServer(.post, path, body, JSONEncoding.default, header, completionHandler)
并在标头部分传递标头值:
Alamofire.request(url!, method: method, parameters: body, encoding: encoding, headers: headers)
并检查是否有错误。在
print(response.error?.localizedDescription)
中打印
.failure
在名为
requestServer
的函数中,您正在发送 headers nil
,请同时传递标头。
Alamofire.request(url!, method: method, parameters: body, encoding: encoding, headers: nil).responseJSON{ (response) in
应该是这样的
Alamofire.request(url!, method: method, parameters: body, encoding: encoding, headers: headers).responseJSON{ (response) in
尝试一下。
更新
下面的代码工作
let params = ["test":"123"]
Alamofire.request("url", method: .post, parameters: params, encoding: URLEncoding(), headers: nil).responseJSON { (test) in
}