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!

Upvotes: 0

Views: 1316

Answers (2)

PPL
PPL

Reputation: 6565

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

    }

Upvotes: 0

Chanchal Chauhan
Chanchal Chauhan

Reputation: 1560

Pass JSONEncoding.default in method to send JSON as given:

requestServer(.post, path, body, JSONEncoding.default, header, completionHandler)

And pass header value in your header section:

Alamofire.request(url!, method: method, parameters: body, encoding: encoding, headers: headers)

And also check for the error. Print print(response.error?.localizedDescription) in .failure

Upvotes: 1

Related Questions