如何在 iPhone/iOS 中以程式設計方式請求定位服務許可權?


在 ios 中,我們可以使用 CLLocationManager 來透過 Swift 請求定位服務許可權。

我們藉助一個示例專案來完成此項操作。因此,建立一個新專案。首先,我們必須建立一個 locationManager 物件,以便在您的檢視控制器中。

var locationManager = CLLocationManager()

現在,我們首先需要檢查裝置上是否啟用定位服務。為此,我們將使用

CLLocationManager.locationServicesEnabled() 函式,它返回一個布林值,顯示裝置上的定位服務是否處於活動狀態。

if CLLocationManager.locationServicesEnabled() {
   print("permissions allowed")
} else {
   locationManager.requestAlwaysAuthorization()
   locationManager.requestWhenInUseAuthorization()
}

在上面的示例中,如果啟用定位服務,則我們列印“permissions allowed”,否則,我們會請求兩種型別的授權,alwaysInUse 和 WhenInUse 授權。

現在,我們看另外一個示例,我們將看到在裝置上啟用定位服務時授予哪種型別的許可權。

我們將使用 CLLocationManager.authorizationStatus() 方法,它向我們返回已授予的授權型別。它是一個列舉,具有 5 個可能的值。

根據 Apple 官方文件,列舉具有以下值。

notDetermined, restricted, denied, authorized, authorizedWhenInUse。

我們看看另外一個示例。

if CLLocationManager.locationServicesEnabled() {
   switch CLLocationManager.authorizationStatus() {
      case .authorizedAlways,.authorizedWhenInUse : print("authorized.")
      case .denied,.restricted,.notDetermined : print("not authorized.")
   }
}

更新於: 30-Jul-2019

217 次瀏覽

開啟您的 職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.