在后台连续 iOS 位置更新

continuous iOS location updates in background

我正在尝试创建一个简单的 iOS 应用程序,它将在后台持续跟踪位置并在用户进入特定区域时以高精度通知(不想使用区域监控,因为它对于我想要的东西来说不够准确或不够快)。

此应用程序在前台运行良好,但一旦我进入后台,它就无法运行。

我创建了一个测试应用程序来研究后台位置更新的工作原理。我制作了一个简单的应用程序,当位置更新发生时(到日志)只打印一条消息。

我看到的是,在前台模式下,更新按预期发生,但是当我锁定我的 phone 并且应用程序切换到后台时,位置更新发生大约 30 秒然后停止。 Apple 文档(我能找到)中没有提及解释此行为。

我确保在 info.plist 中启用了后台处理(在 "capabilities" --> "background modes" --> "location updates" 中完成)

这是我用来测试的代码:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

let locationManager = CLLocationManager() 
var counter = 0
override func viewDidLoad() {
    super.viewDidLoad()

    // configure location updates
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = 0.1
    locationManager.pausesLocationUpdatesAutomatically = false

    locationManager.requestAlwaysAuthorization()

    locationManager.startUpdatingLocation()

}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print("location updated! \(counter)")
    counter = counter + 1
}

关于我可能遗漏的任何想法?我尝试了不同的位置精度设置(例如 BestForNavigation 等),但没有任何变化。

谢谢。

我认为这可能是答案: allowsBackgroundLocationUpdates.

Apps that want to receive location updates when suspended must include the UIBackgroundModes key (with the location value) in their app’s Info.plist file and set the value of this property to true.

...

The default value of this property is false.

你要设置吗?

您必须将此添加到您的 plist 中:

<key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>

添加这个

locationManager.allowsBackgroundLocationUpdates = true

您可以添加这两行使其在后台模式下工作:

locationManager!.allowsBackgroundLocationUpdates = true
locationManager!.pausesLocationUpdatesAutomatically = false