iOS獲取使用者位置
阿新 • • 發佈:2018-12-12
第一種是使用期間獲取位置:
Info.plist裡面新增Privacy - Location When In Use Usage Description及描述文字比如:XX想使用您的地理位置資訊
調起詢問使用者:locationManager.requestWhenInUseAuthorization()
第二種是始終獲取位置:
1.選中專案Target->Capabilities->開啟Background Modes開關->勾選Location updates;
2.Info.plist裡面新增Privacy - Location Always and When In Use Usage Description 及描述文字比如:XX想使用您的地理位置資訊
調起詢問使用者:locationManager.requestAlwaysAuthorization()
程式碼:
import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { var locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self //使用期間獲取位置 // locationManager.requestWhenInUseAuthorization() //始終獲取位置 locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location= locations.last else { return } let latitude = location.coordinate.latitude let longitude = location.coordinate.longitude print(String(format: "latitude = %.4f, longitude = %.4f", latitude, longitude)) } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error) }