【问题标题】:How to track user location across all view controllers in an ios app?如何在 ios 应用程序中跨所有视图控制器跟踪用户位置?
【发布时间】:2019-06-07 03:40:05
【问题描述】:
我正在构建一个应用程序,该应用程序在应用程序打开时跟踪用户位置并使用 geofire 进行查询。我想从用户可能打开的任何视图控制器保持位置更新。我想知道如何做到这一点。
目前,我在主视图控制器中设置了 geofire 和位置跟踪。为了让位置跟踪在所有视图控制器中工作,我是否必须对每个单独的视图控制器进行编码以跟踪位置,或者我可以将代码放入例如应用程序委托文件中吗?
【问题讨论】:
标签:
ios
swift
firebase
geofire
【解决方案1】:
把它放在appdelegate.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)")
}
【解决方案3】:
也许这段代码会起作用,但你必须在你的所有视图控制器中使用它
var LocationManager = CLLocationManager()
LocationManager.requestWhenInUseAuthorization()
if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways){
print("currentLocation = \(LocationManager.location)")
}