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?
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.
Alamofire is built on top of URLSession and the Foundation URL Loading System.
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.
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!)
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With