在 Swift 中等待异步操作完成 [英] Wait For Asynchronous Operation To Complete in Swift
问题描述
我不知道如何处理这种情况,因为我对 iOS 开发和 Swift 非常陌生.我正在执行这样的数据获取:
I am not sure how to handle this situation as I am very new to iOS development and Swift. I am performing data fetching like so:
func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!)
{
loadShows()
completionHandler(UIBackgroundFetchResult.NewData)
println("Background Fetch Complete")
}
我的 loadShows() 函数解析从加载到 UIWebView 的网站获取的一堆数据.问题是我有一个在 loadShows 函数中等待 10 秒左右的计时器.这允许页面中的 javascript 在我开始解析数据之前完全加载.我的问题是完成处理程序在我的 loadShows() 之前完成.
My loadShows() function parses a bunch of data it gets from a website loaded into a UIWebView. The problem is that I have a timer that waits for 10 seconds or so in the loadShows function. This allows for the javascript in the page to fully load before I start parsing the data. My problem is that the completion handler completes before my loadShows() does.
我想要做的是为isCompletedParsingShows"添加一个 bool 并让 completionHandler 行等待完成,直到该 bool 为真.处理此问题的最佳方法是什么?
What I would like to do is add a bool for "isCompletedParsingShows" and make the completionHandler line wait to complete until that bool is true. What is the best way to handle this?
推荐答案
您必须将异步函数传递给处理程序以便稍后调用:
you have to pass your async function the handler to call later on:
func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
loadShows(completionHandler)
}
func loadShows(completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
//....
//DO IT
//....
completionHandler(UIBackgroundFetchResult.NewData)
println("Background Fetch Complete")
}
或(恕我直言,更清洁的方式)
添加一个中间的completionHandler
OR (cleaner way IMHO)
add an intermediate completionHandler
func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
loadShows() {
completionHandler(UIBackgroundFetchResult.NewData)
println("Background Fetch Complete")
}
}
func loadShows(completionHandler: (() -> Void)!) {
//....
//DO IT
//....
completionHandler()
}
这篇关于在 Swift 中等待异步操作完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!