Reputation: 339
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?
Upvotes: 14
Views: 17027
Reputation: 62
HttpManager.sharedInstance.getNewestAppList("\(self.numberofPhoto)", offset: "0", device_type: "ios",search: self.strSearch, filter: self.strFilter, onCompletion: { (responseObject: NSDictionary?, error: NSError?) -> Void in
if error != nil {
SwiftLoader.hide()
self.showAlertWithMessage("\(error!.localizedFailureReason!)\n\(error!.localizedRecoverySuggestion!)")
} else {
SwiftLoader.hide()
if responseObject!.valueForKey("status") as! NSString as String == "0" {
self.showAlertWithMessage(responseObject!.valueForKey("message") as! NSString as String)
} else {
self.itemsArray = responseObject!.valueForKey("data") as! NSArray
print(self.itemsArray.count)
self.tableCategoryDetailRef.reloadData()
}
}
})
import Foundation
typealias getResponse = (NSDictionary?, NSError?) -> Void
class HttpManager: NSObject {
var AFManager: AFURLSessionManager?
var strUrl: NSString = "url"
class var sharedInstance:HttpManager {
struct Singleton {
static let instance = HttpManager()
}
return Singleton.instance
}
// MARK: - Method
func getCount(device_type:String, onCompletion: getResponse) -> Void {
let post: String = "device_type=\(device_type)"
let postData: NSData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!
let postLength:NSString = String(postData.length)
let configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
AFManager = AFURLSessionManager(sessionConfiguration: configuration)
let URL: NSURL = NSURL(string: "\(strUrl)/count" as String)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: URL)
urlRequest.HTTPMethod = "POST"
urlRequest.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
urlRequest.HTTPBody = postData
let task = AFManager?.dataTaskWithRequest(urlRequest) { (data, response, error) in
if response == nil {
SwiftLoader.hide()
} else {
let responseDict:NSDictionary = response as! NSDictionary
onCompletion(responseDict,error)
}
}
task!.resume()
}
}
Upvotes: -1
Reputation: 6365
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.
Upvotes: 6
Reputation: 45180
Swift is fully compatible with Objective-C code, so your problem is not connected with Swift itself. In AFNetworking
, the responseObject
can sometimes be nil
. 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.
Upvotes: 8