14

I am trying to get records from Database using Alamofire. I am sending parameters in GET request as below.

let headers : HTTPHeaders = ["x-access-token": "\(t)","username":"\(Base.sharedManager.user)","password":"\(Base.sharedManager.pass)"]
let parm : [String: Any] = ["search_str" : self!.searchStr]
// let searchUrl = Base.sharedManager.URL+"questions/get/"+self!.searchStr
let searchUrl = Base.sharedManager.URL+"questions/get/"

AF.request(searchUrl, method: .get, parameters: parm, encoding:JSONEncoding.default , headers: headers, interceptor: nil).response { (responseData) in
    guard let data = responseData.data else {
        debugPrint("Error getting question data", responseData.error as Any)
        self?.showNoResults()
        return
    }

    do {
        let sResults = try JSONDecoder().decode(SearchResults.self, from: data)
        self!.searchReturn = [sResults]
        self!.qSearchTV.reloadData()
    } catch {
        self?.showNoResults()
        print("Error retriving questions \(error)")
    }                        
}

Got the error below when above code executed: "Error getting question data" Optional(Alamofire.AFError.urlRequestValidationFailed(reason: Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(23 bytes)))

Jon Shier
  • 12,200
  • 3
  • 35
  • 37
Votesapp Team
  • 141
  • 1
  • 1
  • 3

3 Answers3

29

Use URLEncoding.default instead of JSONEncoding.default

AF.request(path, 
          method: .get, 
      parameters: params, 
        encoding: URLEncoding.default, 
         headers: nil)
  .response { (responseData) in

}
Vlad
  • 1,541
  • 1
  • 21
  • 27
8

Alamofire 5 and Apple's 2019 frameworks now produce an error when you try to make a GET request with body data, as such a request is invalid. I would suggest checking to make sure that's what your server is expecting, and if it does really require body data for GET requests, reach out to the API provider and request a change, as no device running Apple's 2019 OSes will be able to make such a request.

Jon Shier
  • 12,200
  • 3
  • 35
  • 37
  • Got the point. The specific reason for passing parameter is, i cant send the non English chars thru URL string like “let searchUrl = Base.sharedManager.URL+"questions/get/"+self!.searchStr“. So I changed this to send thru body in get method. – Votesapp Team Apr 01 '20 at 03:37
  • You can send non-English characters through the URL just fine, you just need to percent encode them first. – Jon Shier Apr 01 '20 at 15:33
8

You have to remove the "parameters" parameter.

Instead of doing this:

AF.request("https://httpbin.org/get",
              method: .get,
              parameters: [:],
              encoding: URLEncoding.httpBody,
              headers: [:])

Do this:

AF.request("https://httpbin.org/get",
              method: .get,
              encoding: URLEncoding.httpBody,
              headers: [:])
neurona.dev
  • 1,347
  • 1
  • 14
  • 12