一尘不染

如何在Swift中将completionHandler Closure与Return结合使用?

swift

我正在尝试向我们提供一个RESTful
API,该API返回一些json数据。我想封装创建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()

所以这是我的问题。我如何做到这一点,使该completeHandler块能够返回类型为“
AnyObject!”的jsonBlob?如果我将代码稍微修改为以下内容:

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的调用会给出编译器警告,提示:

 Could not find an overload for 'dataTaskWithRequest' that accepts the supplied arguments

我不明白 我正在使用正确的语法来返回闭包,如Swift Docs的此页面所述:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html


阅读 312

收藏
2020-07-07

共1个答案

一尘不染

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()
}

然后,您可以执行以下操作:

getSomething() { (response) in
    if let responseArray = response as? Array<MyObject> {
        self.somethings = responseArray
    }
}
2020-07-07