等待在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屋!