每 X 分钟更新一次服务器位置 iOS

问题描述

我尝试在每 X 分钟后将位置从应用更新到 firebase(任何小于 15 分钟的值都很好)。

我为位置启用了后台模式,并在以下方法中尝试上传到 Firestore 文档。

func locationManager(_ manager: CLLocationManager,didUpdateLocations locations: [CLLocation])

问题在日志中我可以看到此方法已被调用,但在后台没有数据上传到 firestore。事实上,我有时在应用程序进入后台后才工作,但之后就完全没有了。

有什么解决方法吗?

解决方法

使用带有 Timer 的代码在 Firestore 中调用更新:

在开始地图调用时编写此代码:

locationManager.startUpdatingLocation()
    locationManager.delegate = self

在您不想停止位置更新之前避免打电话:

locationManager.stopUpdatingLocation()

符合委托方法:

func locationManager(_ manager: CLLocationManager,didUpdateLocations locations: [CLLocation]) {
    guard let location = manager.location else {
        return
    }
    
    self.clLocation = location
    //Firestore condition here

}
,

检查您是否在位置管理器中将 allowedBackgroundLocationUpdates 设置为 true

locationManager?.allowsBackgroundLocationUpdates = true

仅当位置有任何更新时,您才会在后台更新位置。还要检查您是否在位置管理器中提到了任何 distanceFilter。如果是这样,基于此,您将每 X 米获得一次位置更新

locationManager?.distanceFilter = CLLocationDistance(X)

,

使用此代码

locationManager.startUpdatingLocation()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.delegate = self

不要在以下委托方法中停止位置更新。

func locationManager(_ manager: CLLocationManager,didUpdateLocations locations: [CLLocation])