由于它是异步方法,因此您无法返回值,而是遵循完成处理程序模式,包括作为参数返回的数据:
func performAllMatchesQueryWithCompletionHandler(completionHandler: (UIBackgroundFetchResult, [GTLUserUser]?, ErrorType?) -> ()) {
let query = GTLQueryUser.queryForUserList()
query.userBucket = "messages-20-messagestabletes-1465782960"
service.executeQuery(query) { ticket, response, error in
guard error == nil else {
completionHandler(.failed, nil, error)
return
}
if let userCollection = response as? GTLUserCollection, let newUsers = userCollection.items() as? [GTLUserUser] {
completionHandler(.newData, newUsers, nil)
} else {
completionHandler(.noData, nil, nil)
}
}
}
我从你的使用推断UIBackgroundFetchResult
,您正在执行后台提取。如果是这样,你的performFetchWithCompletionHandler
可能看起来像这样:
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
performAllMatchesQueryWithCompletionHandler { fetchResult, users, error in
switch fetchResult {
case .failed:
// do whatever you want if there was an error
case .noData:
// do whatever you want when there is no data
case .newData:
// do whatever you want with `users`, presumably updating your model or what have you
}
completionHandler(fetchResult)
}
}
然后你可以从调用这个方法viewDidLoad
或任何适合您的应用程序的地方。
请注意,我删除了方法名称上的前导下划线,因为这不是 Swift 中的常见约定,但您可以随意调用您的方法。而我又重新命名了_getAllMatches
to performAllMatchesQueryWithCompletionHandler
,因为它更清楚地表明您正在执行异步查询。
在评论中,您说您没有进行后台提取,而是正在填充表。所以你可能会这样做:
func retrieveDataForTableView(tableView: UITableView) {
performAllMatchesQueryWithCompletionHandler { fetchResult, users, error in
switch fetchResult {
case .failed:
// do whatever you want if there was an error
case .noData:
// do whatever you want when there is no data
case .newData:
// do whatever you want with `users`, presumably updating your model or what have you
// once you've updated your model, you can reload the table:
tableView.reloadData()
}
}
}
请注意,我假设此完成处理程序正在主线程上运行。如果没有,你会想要dispatch_async(dispatch_get_main_queue()) { ... }
更新模型并调用的代码reloadData
.
就我个人而言,我不会倾向于使用UIBackgroundFetchResult
for my performAllMatchesQueryWithCompletionHandler
如果我没有真正进行后台获取。我可能会使用我自己的枚举,以避免对该代码的意图产生任何混淆。