首页 > 解决方案 > 如何在 ios 应用程序中跨所有视图控制器跟踪用户位置?

问题描述

我正在构建一个应用程序,该应用程序在应用程序打开时跟踪用户位置并使用 geofire 查询它。我想从用户可能打开的任何视图控制器保持位置更新。我想知道如何做到这一点。

目前,我在主视图控制器中设置了地理火灾和位置跟踪。为了让位置跟踪在所有视图控制器中工作,我是否必须编写每个单独的视图控制器来跟踪位置,或者我可以将代码放入例如应用程序委托文件中?

标签: iosswiftfirebasegeofire

解决方案


将其放入应用程序 delegate.swift

let locationManager = CLLocationManager()


self.locationManager.requestAlwaysAuthorization() 

// For use in foreground
self.locationManager.requestWhenInUseAuthorization()

if CLLocationManager.locationServicesEnabled() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.startUpdatingLocation()
}

//Here Get Late long.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    print("locations = \(locValue.latitude) \(locValue.longitude)")
}

推荐阅读