如何在 iOS 上執行時請求位置許可權


要請求位置許可權,我們將使用 Apple 的 CLLocationManager 類。您可以使用此類的例項來配置、啟動和停止核心位置服務。

您可以在此處閱讀有關 CLLocationManager 類的更多資訊。

 https://developer.apple.com/documentation/corelocation/cllocationmanager

iOS 應用可以支援兩種級別的位置訪問。

  • 使用應用期間 - 應用可以在應用使用時訪問裝置的位置。這也被稱為“使用時授權”。

  • 始終 - 應用可以在應用使用時或後臺訪問裝置的位置。

這裡我們將使用使用時授權:僅在您的應用執行時請求使用位置服務的授權。

 https://developer.apple.com/documentation/corelocation/choosing_the_authorization_level_for_location_services/requesting_when-in-use_authorization

步驟 1 - 開啟 Xcode,選擇“單檢視應用程式”,將其命名為 LocationServices。

步驟 2 - 開啟 Main.storyboard 並新增一個按鈕,將其命名為 getLocation。

步驟 3 - 在 ViewController.swift 中新增按鈕的 @IBAction。

@IBAction func btnGetLocation(_ sender: Any) {
}

步驟 4 - 匯入 Corelocation 以使用位置類。 import CoreLocation

步驟 5 - 開啟您的 info.plist(要在應用執行時啟用位置更新許可權,需要一個特殊的鍵)。右鍵單擊並選擇“新增行”。輸入以下值。

步驟 6 開啟 ViewController.swift 並建立 CLLocationManager 的物件,

let locationManager = CLLocationManager()

步驟 7 - 在 ViewController.swift 中,在按鈕操作中新增以下程式碼,

@IBAction func btnGetLocation(_ sender: Any) {
   let locStatus = CLLocationManager.authorizationStatus()
   switch locStatus {
      case .notDetermined:
         locationManager.requestWhenInUseAuthorization()
      return
      case .denied, .restricted:
         let alert = UIAlertController(title: "Location Services are disabled", message: "Please enable Location Services in your Settings", preferredStyle: .alert)
         let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
         alert.addAction(okAction)
         present(alert, animated: true, completion: nil)
      return
      case .authorizedAlways, .authorizedWhenInUse:
      break
   }
}

authorizationStatus 將當前授權狀態返回到 locStatus。使用時授權在應用處於前臺時獲取位置更新。當位置服務被停用時,使用者將看到一條帶有“位置服務已停用”訊息的警報。

讓我們執行應用程式,

更新於: 2019-07-30

1K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告