当应用程序终止时,位置后台模式是否在 swift 中工作?

Does the location background mode work in swift when the app is terminated?

现在,我正在尝试为我的应用实现位置背景模式。当用户位置更新时,我将安排一个通知(最终我会有条件地安排它们,但现在我只是安排它们所以我知道它有效)。我有以下代码:

 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        currentLocation = location
    }
    if UIApplication.shared.applicationState == .background {
    // if the app is in the background
         let notif = UNMutableNotificationContent()
    notif.title = "Location was updated"
    var message = " "
    notif.body = message
    let identifier = String(arc4random())
    var dc = DateComponents()
    var date = Date()
    date = Calendar.current.date(byAdding: .second, value: 3, to: date)!
    dc.hour = Calendar.current.component(.hour, from: date)
    dc.minute = Calendar.current.component(.minute, from: date)
    dc.second = Calendar.current.component(.second, from: date)
    let notifTrigger = UNCalendarNotificationTrigger(dateMatching: dc, repeats: false)
    let request = UNNotificationRequest(identifier: identifier, content: notif, trigger: notifTrigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
        if error != nil {
            print(error!)
        } else {
            print("Notification scheduled!")
        }
    })

这在应用程序处于后台时效果很好,但是当应用程序终止时,不会调用我的函数,并且不会传递通知。我的问题是:Swift 这可能吗?还是我正在使用的 locationManager 功能仅在应用程序处于后台但未终止时才有效?

旁注:我试过取出 if UIApplication.shared.applicationState == .background 但没有解决问题

这是可能的。移动应用程序,以便触发位置更新。检查精度为 100 米并移动您的设备或使用模拟器模拟位置。我假设您已经授予 Use Location Always Permission

当您终止该应用程序时,正常*位置服务将停止,直到您从非后台状态运行 startUpdatingLocation


*访问位置服务、区域监控、重要的位置更改 不是 正常的位置跟踪,并且在 OS 级别而不是应用程序级别进行管理。

非正常位置跟踪不会在应用程序终止后停止。