How can I print the json content of the response from post request in Alamofire in swift?
Asked Answered
C

2

8

Ok, so I'm using alamofire and the parameters I'm passing are valid. Here is the code so far:

Alamofire.request(.POST, "http://mywebservice.com", parameters: myparameters)
.response { (request, response, data, error) in
    if(error != nil){
        print("error= \(error)")
    }else{
        print("there was no error so far ")
        print(data)
        var json = JSON(data!)

        print(json) //prints unknown
        print(json["id"]) //prints null      
        }
    }
}

I tried different things but so far nothing worked. I'm using alamofire and swiftyjson, the response json that comes from webservice is:

{
  "id": "432532gdsg",
  "username": "gsdgsdg"
}

and I want to print both values separately in case of success. How can I do it?

Catalyst answered 12/3, 2016 at 16:36 Comment(3)
Let's try this: https://mcmap.net/q/1470258/-swiftyjson-to-read-local-file (it's about the init for JSON() and, if I guess right, may help you)Seamstress
yeah, that was that, thank you! I can either remove this question or - when you post it as an answer - I will accept it and the question gets closed by itself, your call, thanks :)Catalyst
You're welcome! The two questions are different, so I've made a specific answer for this one too. Thank you.Seamstress
S
4

Your issue comes from this line:

var json = JSON(data!)

The JSON() initializer from SwiftyJSON can take several type of inputs.

When you don't specify the type in the init, SwiftyJSON tries to infer the type itself.

Unfortunately it sometimes fails silently because it will have misinterpreted the input.

So, when using SwiftyJSON with NSData, the solution is to specify the "data:" parameter for the JSON initializer:

var json = JSON(data: data!)
Seamstress answered 12/3, 2016 at 16:48 Comment(0)
S
2

Try this

Alamofire.request(.POST, "http://mywebservice.com", parameters : myparameters , encoding : .JSON )
    .responseData{ response in
            let json = JSON(data.response.result.value!)
            print(json)
            let id=json["id"]
            let username=json["username"]
            print(id)
            print(username)          
}
Spiers answered 12/3, 2016 at 16:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.