[英]can we get location updates in IOS swift in a regular intervel of time even when app is not running in foreground
[英]How to get location update in ios using swift even when the app is running in background
我正在開發一個應用程序,我需要定期更新用戶的位置,但是當應用程序暫停或在后台運行時,我無法獲得位置更新。 我還在功能中啟用了后台位置更新。
viewDidLoad代碼:
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.allowsBackgroundLocationUpdates = true
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
let user=FIRAuth.auth()?.currentUser?.displayName
if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse){
locationManager.requestLocation()
location=locationManager.location
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
//updating to database
ref.child("\(user!)/lat").setValue(location.coordinate.latitude)
ref.child("\(user!)/long").setValue(location.coordinate.longitude)
//location=locationManager.location
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
location=locations[locations.count-1]
}
啟用位置更新 - >背景模式 - >功能
我正在使用這種方法在后台獲取位置。 此方法在AppDelegate類中編寫
func getLocation() {
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
if self.locationManager.responds(to: #selector(self.requestAlwaysAuthorization)) {
self.locationManager.requestAlwaysAuthorization()
}
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
if !CLLocationManager.locationServicesEnabled() {
// location services is disabled, alert user
var servicesDisabledAlert = UIAlertView(title: "Alert", message: "Location service is disable. Please enable to access your current location.", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "")
servicesDisabledAlert.show()
}
else {
self.locationManager.startUpdatingLocation()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.