【问题标题】:startMonitoringSignificantLocationChanges not starting instantlystartMonitoringSignificantLocationChanges 未立即启动
【发布时间】:2021-01-30 23:14:21
【问题描述】:

我正在开发一个导航应用程序,一切都在终止、后台和前台状态下工作。 但在终止状态的一种情况下,startMonitoringSignificantLocationChanges 不会自行处理。

问题是

  • 当我启动 startMonitoringSignificantLocationChanges 并杀死应用程序时,我会在 0.5-1 公里后得到位置事件,因为它从我的初始位置绘制直线到我得到的第一个位置事件。但是当位置事件开始时来了就一切顺利
  • 在旅行途中再次出现同样的问题,我打开应用程序检查我的路线状态然后终止应用程序,位置事件再次在 0.5-1 公里后开始出现,并绘制了一条直线。

代码是直的

    significantLocationManager = CLLocationManager()
    significantLocationManager?.allowsBackgroundLocationUpdates = true
    significantLocationManager?.pausesLocationUpdatesAutomatically = false
    significantLocationManager?.requestAlwaysAuthorization()

并在用户需要时调用跟踪

significantLocationManager?.startMonitoringSignificantLocationChanges()

Rest 我已经处理了应用委托中的传入位置事件以保存在数据库中。

所以问题是我应该如何处理这种画直线的场景?

【问题讨论】:

    标签: ios swift location cllocationmanager


    【解决方案1】:

    来自Apple documentation

    只要设备从之前的通知移动 500 米或更远,应用程序就会收到通知。它不应期望通知的频率超过每五分钟一次。如果设备能够从网络中检索数据,则位置管理器更有可能及时发送通知。

    如果您需要尽快接收位置更新,我建议您使用 startUpdatingLocation() 和所需的 distanceFilterCLLocationManager

    【讨论】:

    • 我的应用程序处于终止状态,我猜 startUpdatingLocation 只能在前台和后台工作?
    • 是的。这是最糟糕的事情。在终止状态下,您只能收到重大的位置更改。
    【解决方案2】:

    您可以在后台模式下使用位置更新。来自Apple documentation

    当您启动重大更改位置服务时,最近 缓存的值可能会立即报告给您的委托。作为新 获取位置数据后,位置管理器调用您的代理 具有更新值的 locationManager(_:didUpdateLocations:) 方法。 位置参数始终包含至少一个位置,并且可能 包含多个。位置总是按顺序报告 它们是确定的,所以最近的位置总是 数组中的最后一项,如清单 2 所示。

    func locationManager(_ manager: CLLocationManager,  didUpdateLocations locations: [CLLocation]) {
       let lastLocation = locations.last!
                   
       // Do something with the location. 
    }
    

    在这里您将获得设备中最后缓存的位置,当然如果您的设备中打开了位置服务,它应该非常精确。

    另一件要知道的是。来自 Apple 的备注:

    重大变化定位服务需要授权。为了 请求定位服务授权的更多信息。

    【讨论】:

      猜你喜欢
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-05
      • 1970-01-01
      • 2011-08-10
      • 2012-05-13
      • 1970-01-01
      相关资源
      最近更新 更多