我正在尝试给我们一个返回一些json数据的RESTful API。我想封装创建HTTP请求的代码,并使用自己的方法设置头,所以我可以通过输入一个url String来调用它,然后让该方法返回一个JSON对象。
在下面的代码片段中,我已经创建了请求对象并设置了头文件,并调用该变量“req”。我没有声明任何名为data,response或者error的对象。我有以下代码正确打印出一个JSON对象
let sesh = NSURLSession.sharedSession() let dataTask = sesh.dataTaskWithRequest(req,completionHandler: {(data,response,error) in var jsonError : NSError? let jsonBlob = NSJSONSerialization.JSONObjectWithData(data,options: NSJSONReadingOptions.MutableLeaves,error: &jsonError) println(jsonBlob) }); dataTask.resume()
所以这是我的问题。我如何做到这一点,使得这个完整的HANDLE块能够返回jsonBlob,它的类型是“AnyObject!”?如果我稍微修改代码如下:
let sesh = NSURLSession.sharedSession() let dataTask = sesh.dataTaskWithRequest(req,error) -> AnyObject! in var jsonError : NSError? let jsonBlob : AnyObject! = NSJSONSerialization.JSONObjectWithData(data,error: &jsonError) return jsonBlob }); dataTask.resume()
那么该程序将不会作为对dataTaskWithRequest的调用进行编译:completionHandler给出一个编译器警告:
Could not find an overload for 'dataTaskWithRequest' that accepts the supplied arguments
func getSomething(callback: (Array<AnyObject>) -> ()) { var dataTask = NSURLSessionDataTask() dataTask = session.dataTaskWithRequest(request) { (data,error) in if (error == nil) { var callbackArray = Array<MyObject>() let responseDict = NSJSONSerialization.JSONObjectWithData(data,options: .MutableContainers,error: nil) as NSDictionary let response = responseDict.objectForKey("response_key") as NSDictionary let array = response.objectForKey("array_key") as NSArray for item: AnyObject in array { var arrayItem = MyObject(dict: item as NSDictionary) callbackArray.append(arrayItem) } callback(callbackArray) } else { // handle an error } } dataTask.resume() }
那么你可以做一些事情:
getSomething() { (response) in if let responseArray = response as? Array<MyObject> { self.somethings = responseArray } }