Search code examples
swiftalamofireswift5

Alamofire Request call with: Parameters, Headers and Body not working


I have two questions with regards to the Alamofire code below.

My JSON fails if I remove the ?action=heartbeat at the end of the URL even though I have action = heartbeat in the parameters, why?

How do I add my JSON data/body in the AF.request code below?

let urlString   = "https://intelipos.dynalias.net/ioc/rest.asp?action=heartbeat"
let parameters  = ["action":"heartbeat"]
let headers: HTTPHeaders = ["Content-Type":"application/json"]

AF.request(urlString, method: .post, parameters: parameters, encoding:  URLEncoding.httpBody, headers: headers).responseJSON { response in
  switch response.result {
  case .success:
    print("Validation Successful")
  case let .failure(error):
    print(error)
  }
}

Solution

  • Question One

    You need to encode as a querystring

    let urlString   = "https://intelipos.dynalias.net/ioc/rest.asp"
    let parameters  = ["action":"heartbeat"]
    let headers: HTTPHeaders = ["Content-Type":"application/json"]
    
    AF.request(urlString, method: .post, parameters: parameters, encoding:  URLEncoding.queryString, headers: headers).responseJSON { response in
      switch response.result {
      case .success:
        print("Validation Successful")
      case let .failure(error):
        print(error)
      }
    }
    

    Question Two

    You have to prepare an encodable model and pass it in parameters argument and set encoding to JSONEncoding.default

    Refer this article: https://medium.com/whoknows-swift/swift-4-decodable-encodable-3085305a9618