如何在Swift中将completionHandler Closure与Return结合使用? [英] How to use completionHandler Closure with return in Swift?
问题描述
我正在尝试为我们提供一个RESTful API,该API返回一些json数据。我想封装创建HTTP请求并在其自己的方法中设置标头的代码,以便可以通过输入url String来调用它,然后让该方法返回JSON对象。
I am trying to us a RESTful API that returns some json data. I want to encapsulate the code that creates the HTTP Request and sets the headers in its own method so I can call it by entering a url String and then have the method return a JSON object.
在以下代码段中,我已经创建了请求对象并设置了标头,并将该变量称为 req。我尚未声明任何名为data,response或error的对象。我有以下代码可以正确打印出JSON对象
In the following snippet of code, I have already created the request object and set the headers, and I call that variable "req". I have not declared any objects named data, response, or error. I have the following code that correctly prints out a JSON object
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()
这是我的问题。我如何做到这一点,以便该completeHandler块能够返回类型为 AnyObject!的jsonBlob?如果我将代码稍微修改为以下内容:
So here's my question. How do I make it so that this completionHandler block is able to return the jsonBlob, which is of type "AnyObject!"? If I modify the code slightly to be the following:
let sesh = NSURLSession.sharedSession()
let dataTask = sesh.dataTaskWithRequest(req, completionHandler: {(data, response, error) -> AnyObject! in
var jsonError : NSError?
let jsonBlob : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves, error: &jsonError)
return jsonBlob
});
dataTask.resume()
然后程序将不会编译为调用dataTaskWithRequest:completionHandler会给出编译器警告,提示:
then the program will not compile as the call to dataTaskWithRequest:completionHandler gives a compiler warning saying:
Could not find an overload for 'dataTaskWithRequest' that accepts the supplied arguments
我不明白。我正在使用正确的语法来返回闭包,如Swift Docs的本页中所述:
I don't understand this. I'm using the correct syntax for returning closures, as is given in this page of the Swift Docs:
推荐答案
func getSomething(callback: (Array<AnyObject>) -> ()) {
var dataTask = NSURLSessionDataTask()
dataTask = session.dataTaskWithRequest(request) { (data, response, 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()
}
然后您可以执行以下操作:
Then you could do something like:
getSomething() { (response) in
if let responseArray = response as? Array<MyObject> {
self.somethings = responseArray
}
}
这篇关于如何在Swift中将completionHandler Closure与Return结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!