How to use completionHandler Closure with return in Swift?

后端 未结 4 1319
轮回少年
轮回少年 2020-12-02 09:52

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 cal

相关标签:
4条回答
  • 2020-12-02 10:08
    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
        }
    }
    
    0 讨论(0)
  • 2020-12-02 10:10

    The completion handler can't return anything because the closure you have to supply has to be of return type Void and not AnyObject!.

    func dataTaskWithRequest(_ request: NSURLRequest!,
       completionHandler completionHandler: ((NSData!,
                                  NSURLResponse!,
                                  NSError!) -> Void)!) -> NSURLSessionDataTask!
    
    0 讨论(0)
  • 2020-12-02 10:14

    I came across a similar issue when trying to update info in a central DB based on content was pulling from CloudKit. The patterns for pulling CK data all have these asynchronous completion handlers which allow no return value.

    Since I wanted to be able to re-use similar code in different contexts, I separated the CK calls out into their own class and defined a delegate protocol that I made the core class conform to. Within the completion handlers I sent data retrieved from the CK calls back to where I want them stored via delegate methods.

    Easy peasy.

    0 讨论(0)
  • 2020-12-02 10:18

    as you see here, the dataTaskWithRequest:completionHandler: has a completion handler with no expected return value.

    completion handler's interface

    that means the NSURLSession instance do not expect any value from you to proceed after calling this method; with other words: you completion closure (or block, if you like) ends the procedure here.

    there is not clear why you'd like sending back anything to the caller via the completion handler.

    0 讨论(0)
提交回复
热议问题