Return object for a method inside completion block

夙愿已清 提交于 2019-12-23 02:34:45

问题


I want to make a method with URL parameter that returns the response of calling that URL. How can I return the data obtained inside a completion block for a method?

class func MakeGetRequest(urlString: String) -> (data: NSData, error: NSError)
{
    let url = NSURL(string: urlString)
    var dataResponse: NSData
    var err: NSError

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
           //How can I return the data obtained here....
    })

    task.resume()
}

回答1:


If you want the MakeGetRequest method to return data obtained via dataTaskWithURL, you can't. That method performs an asynchronous call, which is most likely completed after the MakeGetRequest has already returned - but more generally it cannot be know in a deterministic way.

Usually asynchronous operations are handled via closures - rather than your method returning the data, you pass a closure to it, accepting the parameters which are returned in your version of the code - from the closure invoked at completion of dataTaskWithURL, you call that completion handler closure, providing the proper parameters:

class func MakeGetRequest(urlString: String, completionHandler: (data: NSData, error: NSError) -> Void) -> Void
{
    let url = NSURL(string: urlString)
    var dataResponse: NSData
    var err: NSError

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
        completionHandler(data: data, error: error)
    })

    task.resume()
}

Swift 5 update:

class func makeGetRequest(urlString: String, completionHandler: @escaping (Data?, Error?) -> Void) -> Void {
    let url = URL(string: urlString)!
    var dataResponse: Data
    var err: NSError

    let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, respone, error) -> Void in
        completionHandler(data, error)
    })

    task.resume()
}


来源:https://stackoverflow.com/questions/27953739/return-object-for-a-method-inside-completion-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!