我正在使用NextBus应用程序接口构建一个公交车预测应用程序,它将帮助用户获得预测时间和公交车信息。我已经实现了一个函数,该函数获取用户的当前位置和选定的地址,并返回一个包含10条公交路线的列表,这些路线最大限度地减少了行程和时间。
下面是触发上述函数的@IBAction:
@IBAction func findAWayPressed(_ sender: UIButton) {
// Hide confirm button.
confirmButton.isHidden = true
// Setup loading HUD.
let blue = UIColor(red: 153/255, green: 186/255, blue: 221/255, alpha: 1.0)
SVProgressHUD.setBackgroundColor(blue)
SVProgressHUD.setStatus("Finding a way for you...")
SVProgressHUD.setBorderColor(UIColor.black)
SVProgressHUD.show()
// Finds a list of ten bus routes that minimizes the distance from the user and their destination.
WayFinder.shared.findAWay(startCoordinate: origin!, endCoordinate: destination!)
SVProgressHUD.dismiss()
}问题是,confirmButton.isHidden = true和SVProgressHUD行似乎只有在WayFinder.shared.findAWay()执行之后才能执行任何操作。在被SVProgressHUD.dismiss()立即关闭之前,HUD会显示一小段时间。
下面是findAWay函数:
func findAWay(startCoordinate: CLLocationCoordinate2D, endCoordinate: CLLocationCoordinate2D) {
// Get list of bus routes from NextBus API.
getRoutes()
guard !self.routes.isEmpty else {return}
// Initialize the the lists of destination and origin stops.
closestDestinations = DistanceData(shortestDistance: 1000000, stops: [])
closestOrigins = DistanceData(shortestDistance: 1000000, stops: [])
// Fetch route info for every route in NextBus API.
var routeConfigsDownloaded: Int = 0
for route in routes {
// Counter is always one whether the request fails
// or succeeds to prevent app crash.
getRouteInfo(route: route) { (counter) in
routeConfigsDownloaded += counter
}
}
while routeConfigsDownloaded != routes.count {}
// Iterate through every stop and retrieve a list
// of 10 possible destination stops sorted by distance.
getClosestDestinations(endCoordinate: endCoordinate)
// Use destination stop routes to find stops near
// user's current location that end at destination stops.
getOriginStops(startCoordinate: startCoordinate)
// Sort routes by adding their orign distance and destination
// distance and sorting by total distance.
getFoundWays()
}
private func getRouteInfo(route: Route, completion: @escaping (Int) -> Void) {
APIWrapper.routeFetcher.fetchRouteInfo(routeTag: route.tag) { (config) in
if let config = config {
self.routeConfigs[route.tag] = config
} else {
print("Error retrieving route config for Route \(route.tag).")
}
completion(1)
}
}为什么@IBAction中的代码不能按顺序执行?为什么在调用findAWay之前,hud不会显示在屏幕上?有什么想法吗?
发布于 2018-08-02 04:10:37
所以,你需要阅读一些关于“主线程”及其工作原理的文章。也许是UNDERSTANDING THE IOS MAIN THREAD
基本上,您要求系统显示HUD,然后执行,我认为这是一个长时间运行和阻塞的操作,然后在主线程中清除所有HUD。
在方法存在之前,系统不可能显示HUD,因为它将是下一个周期(绘制/布局/其他重要内容)的一部分。在这样的情况下,我会倾向于某种"promise“API,比如PromiseKit或Hydra,因为它将大大简化线程的希望。
基本意图是-当在主线程上时,呈现HUD,使用后台线程,执行查询,当查询完成时,取消HUD,但在主线程上执行。
可能看起来像这样..
SVProgressHUD.show()
DispatchQueue.global(qos: .userInitiated).async {
WayFinder.shared.findAWay(startCoordinate: origin!, endCoordinate: destination!)
DispatchQueue.main.async {
SVProgressHUD.dismiss()
}
}现在请记住,永远不要从主线程上下文之外修改UI,如果操作系统检测到这一点,它将使您的应用程序崩溃!
我可能还会考虑使用DispatchSemaphore而不是“狂野奔跑”的while-loop,这样就可以代替..
// Fetch route info for every route in NextBus API.
var routeConfigsDownloaded: Int = 0
for route in routes {
// Counter is always one whether the request fails
// or succeeds to prevent app crash.
getRouteInfo(route: route) { (counter) in
routeConfigsDownloaded += counter
}
}
while routeConfigsDownloaded != routes.count {}你可以用这样的东西..。
let semaphore = DispatchSemaphore(value: routes.count)
// Fetch route info for every route in NextBus API.
var routeConfigsDownloaded: Int = 0
for route in routes {
// Counter is always one whether the request fails
// or succeeds to prevent app crash.
getRouteInfo(route: route) { (counter) in
semaphore.signal()
}
}
semaphore.wait()它将做同样的事情,但效率更高
https://stackoverflow.com/questions/51641405
复制相似问题