作为一个展示MKRouteSteps的好公民

时间:2016-02-29 09:18:53

标签: ios mkmapview cllocationmanager

缺乏更好的头衔......

我正在一个用于跟踪的应用中编写自定义的转弯实施,并使用CLLocationMKMapView发出指示。

获取给定地址的路线,使用返回的折线显示路线,获取ETA和距离并显示所有这些都显得相当简单且易于实施。但是,没有很多指导的一件事是如何在MKRouteStep对象中显示返回的MKRoute。所有在线指南都不需要提及它们,或者只需在表格视图中一次显示它们就可以轻松地跳过它们。显然不是最优雅的解决方案,而且在我看来是一个缺失的关键部分。

我找到的一个解决方案(找不到我在其中看到的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正确方式,但我不知道如何以另一种方式进行操作。

欢迎任何想法/更好的实施

1 个答案:

答案 0 :(得分:0)

所以,首先,它的工作方式是定义最优雅的方式 - 所以如果你有一些处理所有可能性的代码,那么一定要去实现它!

考虑到这一点,对于没有明确崩溃但您的应用已关闭的情况,您是否可以使用AppDelegate中的众多代理电话之一停止监控?

相关问题