iOS Swift 后台位置监控

问题描述 投票:0回答:4

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

我使用 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
ios iphone swift background-process
4个回答
1
投票

为了使位置更新在后台工作,您需要为您的应用程序启用后台模式功能。

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

为此,单击您的目标,转到功能选项卡,启用后台模式并勾选位置更新。更多详情请看截图

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

希望有帮助!


1
投票

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

要启用访问,请点击“设置”>“位置”,然后选择“始终”

您可以显示警报以通知用户并转到设置。

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
}

不要忘记在目标 -> 签名中启用后台模式 能力

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

这就是您在后台实时定位所需要做的全部工作


-1
投票

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

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

启用此模式不会阻止系统暂停 应用程序,但它确实告诉系统应该唤醒应用程序 每当有新的位置数据要传送时。因此,这个键 有效地让应用程序在后台运行以处理位置 每当发生时都会更新。

更多信息请参阅后台执行


-2
投票

查看

CLLocationManager.startMonitoringSignificantLocationChanges()

Apple 文档在这里

© www.soinside.com 2019 - 2024. All rights reserved.