【发布时间】:2016-06-12 06:25:48
【问题描述】:
没有更好的标题...
我正在使用CLLocation 和MKMapView 在一个用于跟踪和指路的应用中编写自定义转弯实现。
获取给定地址的路线,使用返回的折线显示它,获取 ETA 和距离并显示这些似乎相当简单且易于实现。但是,没有太多指导的一件事是如何显示在MKRoute 对象中返回的MKRouteStep。所有在线指南要么不费心提及它们,要么通过简单地在表格视图中一次显示它们来轻松跳过它们。显然不是最优雅的解决方案,在我看来,这是缺少的关键部分。
我确实找到的一个解决方案(找不到我在其中看到的 SO 答案)提到为每个步骤创建一个 CLRegion。所以我没有提前创建自己的实现:
private func drawRouteOnMap() {
viewModel.getRouteForDelivery() { route in
if let route = route {
self.polyline = route.polyline
self.mapView.addOverlay(route.polyline, level: .AboveRoads)
//Add the route steps to the currentRouteSteps array for later retrieval
self.currentRouteSteps = route.steps
//Set the routeStepLabels text property to the first step of the route.
if let step = route.steps.first {
self.routeStepLabel.text = step.instructions
}
//Iterate over the steps in the `MKRoute` object. Create each region to monitor with the identifier set to an Int
var i = 0
for step in route.steps {
let coord = step.polyline.coordinate
let region = CLCircularRegion(center: coord, radius: 20.0, identifier: "\(i)")
self.locationManager.startMonitoringForRegion(region)
i += 1
}
}
}
}
那我就可以听func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {}委托方法了
private func updateUIForRegion(oldRegion:CLRegion) {
if let regionID = Int(oldRegion.identifier),
steps = currentRouteSteps {
//Fetch the step for the next region
let step = steps[regionID + 1]
routeStepLabel.text = step.instructions
}
}
那么当我们退出视图控制器时
@IBAction func shouldDismissDidPress(sender: AnyObject) {
for (_, region) in locationManager.monitoredRegions.enumerate() {
locationManager.stopMonitoringForRegion(region)
}
dismissViewControllerAnimated(true, completion: nil)
}
实际上,这一切都很好。但是事情开始分崩离析的地方是,如果用户在轮流导航 VC 时按下主页按钮,或者应用程序崩溃。即使应用程序被强制关闭,应用程序也不会停止监视设置的区域,直到 locationManager 被告知停止监视它们。我不希望应用程序终止所有区域监控,因为当用户恢复应用程序时导航将不起作用。感觉区域监控并不是真正正确显示MKRouteStep的方式,但我不知道如何以另一种方式做到这一点。
欢迎任何想法/更好的实现
【问题讨论】:
标签: ios mkmapview cllocationmanager