CLLocationManagerDelegate尝试获取用户当前位置失败

时间:2017-12-11 18:50:59

标签: swift core-location

我尝试获取用户当前位置(像谷歌地图一样的蓝点)以及用户当前位置的经度和纬度

PS。我已经在info.plist中添加了NSLocationAlwaysUsageDescription

我试试这个

private var locationManager: CLLocationManager!
private var currentLocation: CLLocation?

override func viewDidLoad() {
    super.viewDidLoad()

    mapView.delegate = self

    locationManager = CLLocationManager()
    locationManager.delegate = self as! CLLocationManagerDelegate
    locationManager.desiredAccuracy = kCLLocationAccuracyBest

    // Check for Location Services

    if CLLocationManager.locationServicesEnabled() {
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    defer { currentLocation = locations.last }

    if currentLocation == nil {
        // Zoom to user location
        if let userLocation = locations.last {
            let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000)
            mapView.setRegion(viewRegion, animated: false)
        }
    }
}

但是当该页面被此行打开时会出现错误

locationManager.delegate = self as! CLLocationManagerDelegate
  

无法将'tramsimulator.ViewController'类型的值(0x10b542c28)转换为'CLLocationManagerDelegate

0 个答案:

没有答案