Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 489
randomuser1 Avatar asked Mar 12 '16 16:03

randomuser1


People also ask

How do I parse JSON response from Alamofire API in Swift?

To parse the response in Alamofire API request, we will use JSONDecoder, which is an object that decodes instances of a data type from JSON objects. The decode method of JSONDecoder is used to decode the JSON response. It returns the value of the type we specify, decoded from a JSON object.

Does Alamofire use URLSession?

Alamofire is built on top of URLSession and the Foundation URL Loading System.

What is the use of Alamofire in Swift?

Alamofire is an HTTP networking library written in Swift. Alamofire helps to improve the quality of code. It is a simpler way to consume REST services. Alamofire is the basic tool for hundreds of projects.


2 Answers

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!)
like image 99
Eric Aya Avatar answered Oct 24 '22 00:10

Eric Aya


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)          
}
like image 22
imagngames Avatar answered Oct 24 '22 00:10

imagngames