返回完成块中方法的对象 [英] Return object for a method inside completion block
问题描述
我想创建一个带有URL参数的方法,该参数返回调用该URL的响应。
如何返回方法的完成块中获得的数据?
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()
}
推荐答案
如果您希望 MakeGetRequest
方法返回通过 dataTaskWithURL
你不能。该方法执行异步调用,这很可能在 MakeGetRequest
已经返回后完成 - 但是更一般地,它不能以确定性的方式知道。
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.
通常,异步操作通过闭包处理 - 而不是返回数据的方法,你向它传递一个闭包,接受在你的代码版本中返回的参数 - 完成 dataTaskWithURL
,您调用完成处理程序关闭,提供适当的参数:
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()
}
这篇关于返回完成块中方法的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!