【问题标题】:Swift - Location Manager not available right awaySwift - 位置管理器无法立即使用
【发布时间】:2020-05-12 18:18:43
【问题描述】:

所以基本上,当应用加载时,它应该将地图以用户位置为中心,但有时会卡在guard let。代码如下:

override func viewDidLoad() {
    super.viewDidLoad()
    mapView.delegate = self
    locationManager.delegate = self
    configureLocationServices()
    addDoubleTap()
}


//Center map around user location
func centerMapOnUserLocation(){
    print("In \(#function)")
    guard let coordinate = locationManager.location?.coordinate else { print("Error getting coordinate"); return}


    let coordinateRegion = MKCoordinateRegion.init(center: coordinate, latitudinalMeters: locationZoomRadius, longitudinalMeters: locationZoomRadius)
    mapView.setRegion(coordinateRegion, animated: true)

    //Setting local latitude and longitude variables to current location
    latitude = "\(coordinate.latitude)"
    longitude = "\(coordinate.longitude)"
    previewDataOnButton()
    print("Centered Map")
}

// MARK: - Location Services

//Request to enable location services
func configureLocationServices(){
    if authorizationStatus == .notDetermined{
        locationManager.requestAlwaysAuthorization()
    } else {
        return
    }
}

//If authorization changes then call centerMapOnUserLocation
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    print("Authorization changed in \(#function). Calling centerMapOnUserLocation")
    centerMapOnUserLocation()
}

}

它似乎卡在centerMapOnUserLocation() 的守卫上。这通过打印语句显示:

locationManager(_:didChangeAuthorization:) 中的授权已更改。打电话 centerMapOnUserLocation

在centerMapOnUserLocation()

获取坐标时出错

我不确定如何解决这个问题。就像我说的,有时它会经过警卫让,有时它会卡住。

【问题讨论】:

  • 从位置管理器获取位置并不是一蹴而就的事情,事实上,它甚至不会在您每次请求时花费相同的时间。该过程是异步的。

标签: swift xcode


【解决方案1】:

在你viewDidLoad添加这一行:

locationManager.startUpdatingLocation()

然后使用这个CLLocationManagerDelegate方法:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    centerMapOnUserLocation()
}

您可以将位置传递到您的方法中并在传递位置之前移动guard let,如下所示:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = locations.last else { return }
    centerMapOnUserLocation(location: location.last)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多