請求定位權限ios
在 iOS 中用戶的位置信息被視爲我的隱私,因此在獲取時須要向用戶請求權限。本篇教程將講述向用戶請求該權限的步驟。開發環境爲 Xcode 8 Beta,運行環境爲 iOS 10。github
打開 Xcode 而後建立一個新的單視圖應用(Single View Application)。編程
如圖所示,點擊 Next。將工程名命名爲 IOS10RequestingPermissionTutorial,自行填寫 Organization Name 和 Organization Identifier。選擇 Swift 做爲編程語言,適配設備選擇 iPhone。swift
編輯 Storyboard。將一個按鈕控件拖入主視圖。雙擊按鈕視圖編輯文字改成 "Get Location"。以下圖所示:bash
打開 Assistant Editor 並確保 ViewController.swift 文件可見。按住 Ctrl 鍵從按鍵控件拖拽到 ViewController 這個類中來建立一個 Action。app
轉到 ViewController.swift 文件並添加如下代碼導入 Conre Location 框架。框架
import CoreLocation
讓 ViewController 遵循 CLLocationManagerDelegate 協議。並修改該類的定義:編程語言
class ViewController: UIViewController, CLLocationManagerDelegate {}
增長如下屬性:ui
let locationMgr = CLLocationManager()
CLLocationManager 是原生的 GPS 座標管理對象。接下來按照如下代碼來實現 getMyLocation 方法:
@IBAction func getLocation() { // 1 let status = CLLocationManager.authorizationStatus() // 2 if status == .notDetermined { locationMgr.requestWhenInUseAuthorization() return } // 3 if status == .denied || status == .restricted { let alert = UIAlertController(title: "Location Services Disabled", message: "Please enable Location Services in Settings", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(okAction) present(alert, animated: true, completion: nil) return } // 4 locationMgr.delegate = self locationMgr.startUpdatingLocation() }
authorizationStatus 對象將返回受權狀態。
保證 app 在前臺運行時,當定位更新後獲取定位。
當定位服務被禁用時,用戶將收到提示。
肯定代理對象爲當前的 ViewController
而後實現 CLLocationManager 的代理方法。
// 1 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let currentLocation = locations.last! print("Current location: \(currentLocation)") } // 2 func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Error \(error)") }
當前位置座標輸出到控制檯。
當定位沒法更新時輸出錯誤緣由。
要在 app 運行時請求 GPS 定位權限,須要在 info.plist 中設置新的屬性鍵(Key)。單擊鼠標右鍵選擇添加行,並輸入如下值:
在 Build 並運行工程時,app 會主動尋求定位受權:
點開控制檯中的位置箭頭,選擇一個預約義的位置。控制檯會打印當前的 GPS 定位。
bash Current location: <+51.50998000,-0.13370000> +/- 5.00m (speed -1.00 mps / course -1.00) @ 9/12/16, 3:25:27 PM Central European Summer Time Current location: <+51.50998000,-0.13370000> +/- 5.00m (speed -1.00 mps / course -1.00) @ 9/12/16, 3:25:28 PM Central European Summer Time Current location: <+51.50998000,-0.13370000> +/- 5.00m (speed -1.00 mps / course -1.00) @ 9/12/16, 3:25:29 PM Central European Summer Time Current location: <+51.50998000,-0.13370000> +/- 5.00m (speed -1.00 mps / course -1.00) @ 9/12/16, 3:25:30 PM Central European Summer Time Current location: <+51.50998000,-0.13370000> +/- 5.00m (speed -1.00 mps / course -1.00) @ 9/12/16, 3:25:31 PM Central European Summer Time Current location: <+51.50998000,-0.13370000> +/- 5.00m (speed -1.00 mps / course -1.00) @ 9/12/16, 3:25:32 PM Central European Summer Time
你能夠在 Github 上的 ioscreator 倉庫中下載 IOS10RequestingPermissionTutorial 的源碼。
本文由 SwiftGG 翻譯組翻譯,已經得到做者翻譯受權,最新文章請訪問 http://swift.gg。