简体   繁体   English

iOS Swift 后台位置监控

[英]iOS Swift Background Location Monitoring

I'm writing an app with background location support.我正在编写一个具有后台位置支持的应用程序。 The app need to track user location points as they drive through towns on delivery routes.该应用程序需要跟踪用户在送货路线上穿过城镇时的位置点。

I use startUpdatingLocation() from CLLocationManager, and everything works fine until the app has been in the background about 15 minutes.我使用 CLLocationManager 中的 startUpdatingLocation(),一切正常,直到应用程序在后台运行大约 15 分钟。

The app then seems to terminate and tracking ends.然后应用程序似乎终止并跟踪结束。

I know this continuous tracking (ie MapMyRun) has to work, but I'm stumped as to how.我知道这种连续跟踪(即 MapMyRun)必须起作用,但我不知道如何进行。

Edit: LocationManager configured as follows编辑: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

In order for the location updates to work in the background you need to enable the Background Mode capability for your app.为了让位置更新在后台工作,您需要为您的应用启用后台模式功能。

If you don't do that the app will terminate in the background after an X amount of time the OS thinks is appropriate.如果您不这样做,应用程序将在操作系统认为合适的 X 时间后在后台终止。

In order to do that Click on your target, go to the capabilities Tab, enable the Background Modes and Tick the location updates.为此,单击您的目标,转到功能选项卡,启用后台模式并勾选位置更新。 See the screenshot for more details查看屏幕截图了解更多详情

BG 模式

Try that and if it is still not working I suggest you upload your location manager code somewhere to take a look.尝试一下,如果它仍然无法正常工作,我建议您将您的位置管理器代码上传到某个地方来查看。

Hope that helps!希望有帮助!

iOS kills location service in background. iOS 在后台终止位置服务。 You need to set it manually in iPhone settings.您需要在 iPhone 设置中手动设置。

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

You can show an alert to inform the user and go to settings.您可以显示警报以通知用户并转到设置。

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
            }
        }
    }

For more accuracy call this method too为了更准确,也调用此方法

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

And don't forget to enable Background Modes in Target -> signing and capabilites并且不要忘记在 Target -> 签名和功能中启用后台模式

last check is to add permission in info.plist最后检查是在 info.plist 添加权限

Thanks all you have to do for live location in background感谢您为后台实时定位所做的一切

Check out查看

CLLocationManager.startMonitoringSignificantLocationChanges()

The Apple documentation here 苹果文档在这里

The location updates your app gets while in the background is completely handled by iOS and out of your apps control.您的应用程序在后台获取的位置更新完全由 iOS 处理,不受您的应用程序控制。

According to Apple's documentation regarding background location services:根据苹果关于后台定位服务的文档:

Enabling this mode does not prevent the system from suspending the app, but it does tell the system that it should wake up the app whenever there is new location data to deliver.启用此模式不会阻止系统暂停应用程序,但它会告诉系统只要有新的位置数据要传送,它就应该唤醒应用程序。 Thus, this key effectively lets the app run in the background to process location updates whenever they occur.因此,此键有效地让应用程序在后台运行,以便在发生位置更新时进行处理。

For more information refer to Background Execution有关更多信息,请参阅后台执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM