skip to Main Content

I am trying to hit alamofire post request but, Getting Request failed with error responseSerializationFailed ( reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed ( error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0})). Please help me to figure out the issue. Thanks.

below is my Api handler method

func apiPostRequest1(parameters:[String:String], url:String,  completionHandler: @escaping (Any?) -> Swift.Void) {
    

    var headers = HTTPHeaders(parameters)
    headers.add(name: "Content-Type", value: "application/x-www-form-urlencoded; charset=UTF-8")
    
    session.request(url,
               method: .post,
               parameters: parameters,
               encoding: URLEncoding.httpBody,
               headers: headers).validate(statusCode: 200..<600).responseJSON{ response in
        switch response.result {
        case .success(let JSON):
            completionHandler(JSON)
        case .failure(let error):
            print("Request failed with error (error)")
            completionHandler(response.response?.statusCode)
        }
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    Below code is working when i removed headers from request.

    func apiPostRequest1(parameters:[String:String], url:String,  completionHandler: @escaping (Any?) -> Swift.Void) {
        
        session.request(url,
                   method: .post,
                   parameters: parameters,
                   encoding: URLEncoding.httpBody).validate(statusCode: 200..<600).responseJSON{ response in
            switch response.result {
            case .success(let JSON):
                completionHandler(JSON)
            case .failure(let error):
                let responseData = String(data: response.data!, encoding: String.Encoding.utf8)
                print(responseData ?? "Error in encoding response data")
                print("Request failed with error (error)")
                completionHandler(response.response?.statusCode)
            }
        }
    }
    

  2. In my case, it was an issue with passing the password parameter.
    I was passing the encoded password
    requestDict["password"] = (parameters?["password"] as? String)?.encodeToBase64()
    I checked with the backend team and I avoided that and passed the same text password
    requestDict["password"] = (parameters?["password"]
    make sure you are passing the correct parameters and correct URL as per API requirements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search