代码改变世界

iOS获取用户位置

2018-12-12 10:02  法子  阅读(642)  评论(0编辑  收藏  举报

第一种是使用期间获取位置:

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)
    }