iosswiftrequestalamofire

AlamoFire Sending Nil


I'm sending a JSON request via Alamofire but, the function is sending nil. Even though I have verified that all items works as they should.

Helper Function:

 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
                }
            }
        }

    }

Function sending 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

Any insight would help!


Solution

  • In this line in your function named requestServer, you are sending headers nil, please pass the headers as well.

    Alamofire.request(url!, method: method, parameters: body, encoding: encoding, headers: nil).responseJSON{ (response) in
    

    It should be like this,

    Alamofire.request(url!, method: method, parameters: body, encoding: encoding, headers: headers).responseJSON{ (response) in
    

    Try it out.

    UPDATE

    Below code working

        let params = ["test":"123"]
        Alamofire.request("url", method: .post, parameters: params, encoding: URLEncoding(), headers: nil).responseJSON { (test) in
    
        }