我有一个包含对象的类,为了使用对象的属性,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()
})
}
}