I'm trying to get a JSON response using Swift.
I sniffed the request and response -> everything ok. However the return value is always nil
.
let httpClient = AppDelegate.appDelegate().httpRequestOperationManager as AFHTTPRequestOperationManager;
let path = "/daten/wfs";
let query = "?service=WFS&request=GetFeature&version=1.1.0&typeName=ogdwien:AMPELOGD&srsName=EPSG:4326&outputFormat=json".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding);
func successBlock(operation: AFHTTPRequestOperation!, responseObject: AnyObject!) {
println("JSON: " + "\(responseObject)")
}
func errorBlock(operation: AFHTTPRequestOperation!, error:NSError!) {
println("Error: " + error.localizedDescription)
}
let urlString = "\(path)" + "/" + "\(query)"
println("urlString: " + httpClient.baseURL.absoluteString + urlString)
I also tried it this way:
httpClient.GET(urlString, parameters: nil,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
println("Success")
println("JSON: " + "\(responseObject)")
},
failure:{ (operation: AFHTTPRequestOperation!, error:NSError!) -> Void in
println("Failure")
})
... But the responseObject
always seems to be nil
EDIT:
Maybe the reason is the possible wrong initialisation in my AppDelegate
:
var httpRequestOperationManager: AFHTTPRequestOperationManager? // JAVA SERVER Client
class func appDelegate() -> AppDelegate {
return UIApplication.sharedApplication().delegate as AppDelegate
}
func configureWebservice() {
let requestSerializer = AFJSONRequestSerializer()
requestSerializer.setValue("1234567890", forHTTPHeaderField: "clientId")
requestSerializer.setValue("Test", forHTTPHeaderField: "appName")
requestSerializer.setValue("1.0.0", forHTTPHeaderField: "appVersion")
let responseSerializer = AFJSONResponseSerializer()
AFNetworkActivityIndicatorManager.sharedManager().enabled = true
// ##### HTTP #####
let baseURL = NSURL(string: "http://data.wien.gv.at");
httpRequestOperationManager = AFHTTPRequestOperationManager(baseURL: baseURL))
httpRequestOperationManager!.requestSerializer = requestSerializer
httpRequestOperationManager!.responseSerializer = responseSerializer
}
Any suggestions what I'm doing wrong?
You can use Swift's interoperability with Objective-C frameworks but now there is an official library out there, let's check it out:
https://github.com/Alamofire/Alamofire
This library is written in native Swift, from the creator of AFNetworking. You will probably want to look for this kind of thing when moving to Swift. I tried it out and it's awesome, like its predecessor.
Swift is fully compatible with Objective-C code, so your problem is not connected with Swift itself. In
AFNetworking
, theresponseObject
can sometimes benil
. This includes cases, where:204 No Content
status code was returned,NSURLErrorCannotDecodeContentData
(e.g. unacceptable content type)Check out #740 and #1280 for more information.