iOS Swift后台位置监控

时间:2018-09-06 08:12:15

标签: ios iphone swift background-process

我正在编写一个具有后台位置支持的应用程序。该应用程序需要跟踪用户在送货路线上穿过城镇的位置点。

我使用CLLocationManager中的startUpdatingLocation(),直到应用程序在后台运行约15分钟为止,一切正常。

然后该应用似乎终止并且跟踪结束。

我知道这种连续跟踪(即MapMyRun)必须有效,但是我对方法感到困惑。

编辑:LocationManager的配置如下

self.locationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation
self.locationManager?.distanceFilter = kCLDistanceFilterNone
self.locationManager?.allowsBackgroundLocationUpdates = true
self.locationManager?.pausesLocationUpdatesAutomatically = false
self.locationManager?.activityType = CLActivityType.automotiveNavigation
self.locationManager?.showsBackgroundLocationIndicator = true

4 个答案:

答案 0 :(得分:0)

要使位置更新在后台运行,您需要为您的应用启用“后台模式”功能。

如果不这样做,该应用程序将在操作系统认为合适的X倍的时间后在后台终止。

为此,请单击目标,转到功能选项卡,启用“后台模式”并勾选位置更新。有关更多详细信息,请参见屏幕截图

BG Modes

尝试一下,如果仍然无法正常工作,建议您将位置管理器代码上传到某处进行查看。

希望有帮助!

答案 1 :(得分:0)

iOS在后台终止位置服务。 您需要在iPhone设置中手动设置它。

To enable access, tap Settings > Location and select Always"

您可以显示警报以通知用户并进入设置。

func checkUsersLocationServicesAuthorization(){
        /// Check if user has authorized Total Plus to use Location Services
        if CLLocationManager.locationServicesEnabled() {
            switch CLLocationManager.authorizationStatus() {
            case .notDetermined:
                // Request when-in-use authorization initially
                // This is the first and the ONLY time you will be able to ask the user for permission
                self.locationManager.delegate = self
                locationManager.requestWhenInUseAuthorization()
                break

            case .restricted, .denied:
                // Disable location features
                let alert = UIAlertController(title: "Allow Location Access", message: "MyApp needs access to your location. Turn on Location Services in your device settings.", preferredStyle: UIAlertController.Style.alert)

                // Button to Open Settings
                alert.addAction(UIAlertAction(title: "Settings", style: UIAlertAction.Style.default, handler: { action in
                    guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                        return
                    }
                    if UIApplication.shared.canOpenURL(settingsUrl) {
                        UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                            print("Settings opened: \(success)")
                        })
                    }
                }))
                alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil))
                self.present(alert, animated: true, completion: nil)

                break

            case .authorizedWhenInUse, .authorizedAlways:
                // Enable features that require location services here.
                let alert = UIAlertController(title: "Allow Location Access", message: "Lookout does not have access to your location while in the background. To enable access, tap Settings > Location and select Always", preferredStyle: UIAlertController.Style.alert)

                // Button to Open Settings
                alert.addAction(UIAlertAction(title: "Settings", style: UIAlertAction.Style.default, handler: { action in
                    guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                        return
                    }
                    if UIApplication.shared.canOpenURL(settingsUrl) {
                        UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                            print("Settings opened: \(success)")
                        })
                    }
                }))
                alert.addAction(UIAlertAction(title: "Not Now", style: UIAlertAction.Style.default, handler: nil))
                self.present(alert, animated: true, completion: nil)

                break
            }
        }
    }

为获得更高的准确性,也请调用此方法

func startLocationService(){
    locationManager.startUpdatingLocation()
    locationManager.startMonitoringSignificantLocationChanges()
    locationManager.pausesLocationUpdatesAutomatically = false
    locationManager.allowsBackgroundLocationUpdates = true
    locationManager.showsBackgroundLocationIndicator = true
}

别忘了在Target中启用后台模式->签名并 Capabilites

最后检查是在info.plist中添加权限

感谢您为后台实时定位所做的一切

答案 2 :(得分:-1)

退房

CLLocationManager.startMonitoringSignificantLocationChanges()

The Apple documentation here

答案 3 :(得分:-1)

您的应用在后台获取的位置更新完全由iOS处理,并且不受应用控制。

根据Apple有关后台定位服务的文档:

  

启用此模式不会阻止系统挂起   应用程序,但是它确实告诉系统应该唤醒应用程序   每当有新的位置数据要传递时。因此,这个关键   有效地使应用程序在后台运行以处理位置   随时更新。

有关更多信息,请参见Background Execution