如何知道异步函数在对象内部何时完成?
问题描述:
我有一个包含对象的类,为了使用对象的属性,NSURLSession必须完成它的异步数据请求。我如何通过一个对象创建一个回调函数来完成该功能,并且可以调用这些属性。如何知道异步函数在对象内部何时完成?
答
你没有给出代码的例子,所以我会写在摘要中。您需要在完成NSURLSession
对象内调用与您的对象一起工作的方法。例如,它可能看起来像这样:
// This is your object
struct SomeData {
var someValue: Int = 0
}
// This is class that use it
class Foo {
var someData: SomeData
init() {
someData = SomeData()
requestData()
}
// This is your function that need to wait for the request
func doActionWithData() {
print(someData.someValue)
}
// This is request
func requestData() {
// Make request with your params
let request = NSMutableURLRequest(...)
...
// For example you do it like this
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in
// here you have data for your object you can get it from
// response and then call function to work with it
self.someData.someValue = ...
self.doActionWithData()
})
}
}