代码之家  ›  专栏  ›  技术社区  ›  LFHS

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

  •  0
  • LFHS  · 技术社区  · 7 年前

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

     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!")
            }
        })
    

    当应用程序在后台时,这非常有效,但当应用程序终止时,我的函数不会被调用,通知也不会被传递。我的问题是:斯威夫特能做到这一点吗?或者 locationManager 如果应用程序是后台的,但没有终止,我只使用work?

    旁注: 我已经试过了 if UIApplication.shared.applicationState == .background 但这并不能解决问题

    2 回复  |  直到 7 年前
        1
  •  1
  •   mfaani    7 年前

    当你终止应用程序时,正常的*位置服务会停止,直到你运行为止 startUpdatingLocation 从非背景状态。


    *访问位置服务、区域监控、重大位置变化 正常位置跟踪,在操作系统级别而不是应用程序级别进行管理。

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

        2
  •  0
  •   ahmed    7 年前

    这是可能的。移动应用程序以触发位置更新。检查准确度为100m,移动设备或使用模拟器模拟定位。我假设您已经授予使用位置始终权限