FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) - ios

I'm trying to read the JSON using Alamofire. Here is my code:
let headers = ["Content-Type": "application/json"]
func getConfirmationCode(params: [String:Any], block: #escaping(_ data : JSON, _ success : Bool) -> Void) {
if let url = URL(string: baseURL + "getConfirmationCode.php") {
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
DispatchQueue.main.async {
if let value = response.result.value {
let json = JSON(value)
block(json, true)
} else {
block(JSON.null, false)
}
}
}
}
}
The JSON is valid, everything works perfectly in Postman, but I can't make it work. None of the suggestions on the web helped (changing the responseJSON to responseString/responseData, changing the JSONEncoding.default to URLEncoding.default, etc.)
Can anyone help me?

You should try to check response in postman in "Preview" tab of response section. sometime it displays proper json in "Pretty" section. but in "Preview" section it many contains some print statements of API response. and those print statements makes problem in json decoding.
also, if you want to get swift code of postman response you can always get it from postman's code feature:
Hope this helps..!

Related

NSLocalizedDescription=The certificate for this server is invalid Alamofire 5.2 Swift

I am trying to create a login screen which uses Alamofire 5.2 to post the request but I seem to get the same error over and over again, I have tried to set up the info.plist file as many have suggested bu it was of no help. I tried to change the method in which I will post which was also of no help.
Please help Me our with this as I have been stuck with this for days with no results.
Request Function:
func loginPlease(){
let params = ["username":self.emailTextBox.text!, "password":self.PasswordTextBox.text!]
let encodeURL = "domain url"
let requestoAPI = AF.request(encodeURL, method: .post, parameters: nil, encoding: JSONEncoding.default, headers:["username":self.emailTextBox.text!, "password":self.PasswordTextBox.text!])
requestoAPI.responseJSON(completionHandler: { (response) -> Void in
print(response.request!)
print(response.result)
print(response.response)
})
}
Alternative function (just to be sure)
func loginPlease(){
let params = ["username":self.emailTextBox.text!, "password":self.PasswordTextBox.text!]
let encodeURL = "domain url"
let requestoAPI = AF.request(encodeURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers:nil)
requestoAPI.responseJSON(completionHandler: { (response) -> Void in
print(response.request!)
print(response.result)
print(response.response)
})
}
Info.plist:
Log:

Swift 5 & Alamofire 5 : GET method ERROR: Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(22 bytes)

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)))
Use URLEncoding.default instead of JSONEncoding.default
AF.request(path,
method: .get,
parameters: params,
encoding: URLEncoding.default,
headers: nil)
.response { (responseData) in
}
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.
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: [:])

getting data from AF.Request response

I need the data from the json response from my Post request call using Alamofire but I cannot access that data for some reason
I tried following along with Alamofire github documentation along with this post get data from AF responseJSON. but neither have helped me.
AF.request("https://mbd.cookcountysupernetwork.com/ap/swift_math_get.asp", method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
print("floop")
}
This is what I see when the code runs
success({
Operand = (
{
A = 12;
},
{
B = 25;
}
);
Operation = Multiply;
Result = 300;
})
so I know the json is there, i just need to access the "Result = 300" so I can set a text box to say "300". but I tried many different methods and I cannot access the information I need from response. Also i do not have a response.result.value which is what almost every post I see about this says to use.
You can access the Result value as,
AF.request("https://mbd.cookcountysupernetwork.com/ap/swift_math_get.asp", method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success(let value):
if let json = value as? [String: Any] {
print(json["Result"] as? Int)
}
case .failure(let error):
print(error)
}
}

Alamofire - Bad request

I am afraid I cannot share the API url. But I have checked on Postman, it works. It is a POST request and following is the response :
{
"user_key": "b0aebdedb15e2beaaf479ca3c4f8227e8e970681"
}
Postman screenshot :
In code, this is the request I am making using Alamofire :
Alamofire.request("some url", method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: ["Content-Type":"application/json"])
.responseObject { (response: DataResponse<User>) in
let userResponse = response.result.value
print("")
}
But userResponse comes to be nil. This is the User object :
import ObjectMapper
class User: Mappable {
var authToken: String?
required init?(map: Map) {
}
func mapping(map: Map) {
self.authToken <- map["user_key"]
}
}
I am using ObjectMapper here.
Assuming the it is not a JSON object, I tried to handle it as a String :
Alamofire.request("some url", method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: ["Content-Type":"application/json"])
.responseString { (response: DataResponse<String>) in
let dataUser = response.data as! Any
let dataUser1 = response.data as! AnyObject
let error = response.error
let code = response.response?.statusCode
print(response.value)
print(response.result.value)
}
Still, nothing. I am not able to retrieve the value. The status code however comes out to be 400 (bad request).
What exactly is it ? JSON object or String ? How do I fix this ?
Just try to replace
this URLEncoding.httpBody to JSONEncoding.default
JSONEncoding.default
Uses JSONSerialization to create a JSON representation of the parameters object, which is set as the body of the request. The Content-Type HTTP header field of an encoded request is set to application/json.
Alamofire reference

Alamofire Error Token (Post) with Swift

My mates and I are working on a iOS Project, and we get stacked in this issue.
We are trying to make a POST request to our API, but all we are getting is a success code but with a reponse of type:
SUCCESS: { detail = "Authentication credentials were not provided."; }
This is our code:
#IBAction func accept(_ sender: Any) {
var comm,cat,dist : String!
comm = observationstwee.text!
print(comm)
let catd = 7
cat = String(catd)
print(cat)
dist = distancetwee.text!
print(dist)
let parameters: Parameters = [
"comment":comm,
"category":cat,
"distance":dist,
"timestamp":time
]
let headers: HTTPHeaders = ["Authorization": "Token \(token!)"]
print(headers.debugDescription)
Alamofire.request("https://llegoelbigotes.ubiqme.es/api/new-travel",parameters: parameters, headers: headers).responseJSON {response in switch(response.result) {
case .success(_):
print(response)
print("Correct Travel")
//changeViewController(storyboard_name: "Main", viewcontroller_name: "tabBarController", context: self)
break
case .failure(_):
print("FAILURE")
}
}
}
As well as with this call:
Alamofire.request("https://llegoelbigotes.ubiqme.es/api/new-travel",method:.post,parameters: parameters,headers:headers, encoding: JSONEncoding.default).validate().responseJSON
We get this:
"Extra argument 'method' in call"
Thank you so much for your help, we are working with Alamofire 4.5 and iOS 11.2
This type of error occurs when one of the parameters it’s not correct, in your example this is probably the “headers” parameter, try:
let headers = ["Authorization": "Token \(token!)"]
And check the Alamofire migration guide, you could use the RequestAdapter protocol.
when you are using post method so you need to provide the method type to the request argument code should be like that
request("https://llegoelbigotes.ubiqme.es/api/new-travel", method:
.post, parameters: parameters, encoding: JSONEncoding.default, headers:
headers).responseJSON(completionHandler:{ responseObject in
})

Resources