AlamoFire发送无

时间:2018-06-11 04:47:06

标签: ios swift api request alamofire

我正在通过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)
    }

enter image description here

任何见解都会有所帮助!

2 个答案:

答案 0 :(得分:1)

在方法中传递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

答案 1 :(得分:0)

在名为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

    }