Search code examples
iosjsonswiftiphonealamofire

Alamofire post request getting **Invalid value around line 1, column 0.**


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)
        }
    }
}

Solution

  • 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)
            }
        }
    }