Search code examples
iosjsonswiftalamofire

Alamofire 4.3 can't send JSON request


Iam Trying to send a JSON request using Alamofire but it's not working as a JSON Request here's my JSON :

{"ClientID":"55050","AdminId":"myemail","Password":"123"}

content-type →  application/json; charset=utf-8

and here's my code :

import Alamofire

func doLogin(username:String ,password:String) {
    let parameters = ["ClientID":"55050" , "AdminId":username,"Password":password]

    Alamofire.request("myurl.com", method: .post, parameters: parameters, encoding: JSONEncoding(options: []) ).responseJSON(completionHandler: {
        response in
        print(response)
    })

and here's the response which i am getting

FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}))


Solution

  • By reading the documentation i just need to put header to set the request as application/json

    so i added extra parameter header :

    let headers: HTTPHeaders = [
                "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
                "Accept": "application/json"
            ]
     Alamofire.request(ApiKeys().login, method : .post , parameters : parameters, encoding: JSONEncoding.default ,  headers: headers).responseJSON { response in
    
            }
    

    and now it's working perfectly thanks everyone for trying to help :)