I use Alamofire
to do requests to a rest service. If the request is successful the server returns a JSON
with content-type application/json
. But if the request fails the server returns a simple String
.
So, I don't know how to handle on it with Alamofire
, because I don't know how the response look like. I need a solution to handle on the different response types.
This code I can use to handle on a successful request:
request(.POST, wholeUrl, parameters: parameters, encoding: .Custom(encodingClosure))
//.validate()
.responseJSON {
(request, response, data, error) -> Void in
//check if error is returned
if (error == nil) {
//this crashes if simple string is returned
JSONresponse = JSON(object: data!)
}
And this code I can use to handle on failed request:
request(.POST, wholeUrl, parameters: parameters, encoding: .Custom(encodingClosure))
//.validate()
.responseString {
(request, response, data, error) -> Void in
//check if error is returned
if (error == nil) {
responseText = data!
}
I've solved my problem:
request(.POST, wholeUrl, parameters: parameters, encoding: .Custom(encodingClosure))
.validate()
.response {
(request, response, data, error) -> Void in
//check if error is returned
if (error == nil) {
var serializationError: NSError?
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data! as! NSData, options: NSJSONReadingOptions.AllowFragments, error: &serializationError)
JSONresponse = JSON(object: json!)
}
else {
//this is the failure case, so its a String
}
}