如何在 Swift 中後臺執行以提供當前位置?
要在 Swift 中獲取後臺位置,我們需要執行以下幾個步驟
獲取使用者的許可權,在你的 info.plist 檔案中新增 Privacy - Location always 和
When in usage Description,Privacy - When in usage description 並新增各自的描述。
之後,你需要匯入 CoreLocation 框架,這將使你能夠使用所有與位置相關的庫和方法。然後,你需要獲得使用者的許可權來使用位置。為此,我們需要建立一個 CLLocationManager 物件並獲取授權。
var locationManager: CLLocationManager? override func viewDidLoad() { super.viewDidLoad() locationManager = CLLocationManager() locationManager?.delegate = self locationManager?.requestAlwaysAuthorization() }
現在,當你執行應用程式並且特定模組需要位置時,它會請求使用者許可權。之後,你可以新增以下程式碼來開始監控位置變化、更新位置等。
locationManager.startUpdatingLocation() locationManager.startMonitoringSignificantLocationChanges() locationManager.allowsBackgroundLocationUpdates = true
完成此操作後,你可以使用 CLLocationManagerDelegate 的 didUpdateLocation 方法將位置更新到你的伺服器後臺。
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { // Hit api to update location }
現在,每當位置更新時,都會呼叫 CLLocationManagerDelegate 的此方法,我們可以在其中編寫將位置更新到伺服器的程式碼。
廣告