更新时间:2023-02-23 11:20:37
如果您希望 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()
}