[英]How to track user location in the background swift
我試圖在后台跟蹤用戶位置,當我們在有和沒有的情況下嘗試使用時,但是每次我最小化應用程序時,位置圖標都消失了,我已經在教程中閱讀過它應該顯示藍色條,但我沒有得到欄我也檢查了背景模式以更新位置
map.showsUserLocation = true
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
// Do any additional setup after loading the view, typically from a nib.
alwaysAuthorization()
}
func alwaysAuthorization(){
if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
locationManager.requestAlwaysAuthorization()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude), span: MKCoordinateSpan (latitudeDelta: 0.2, longitudeDelta: 0.2))
self.map.region = region
print("location \(location!.coordinate.latitude) and \(location!.coordinate.longitude)")
}
您可以使用startMonitoringSignificantLocationChanges()方法代替startUpdatingLocation()
根據文檔:
當設備距其先前的通知500米或更多距離時,應用程序會期望收到通知。 它不應期望通知的頻率超過每五分鍾一次。 如果設備能夠從網絡檢索數據,則位置管理器更有可能及時傳遞通知。
我曾經使用過這種方法並對其進行了測試。 它與蜂窩和wi-fi搭配使用效果很好。
您的問題不清楚。 您在后台運行應用程序時遇到問題嗎? 還是簡單地期望藍色條指示您的應用在后台跟蹤位置?
對於后者,您需要啟用后台位置指示器
locationManager.showsBackgroundLocationIndicator = true
這是我一直在尋找的
locationManager.allowsBackgroundLocationUpdates = true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.