简体   繁体   English

Swift - 位置管理器无法立即使用

[英]Swift - Location Manager not available right away

So basically when the app loads it's supposed to center the map on the user location, but sometimes will get stuck at the guard let .所以基本上当应用程序加载时,它应该将 map 放在用户位置的中心,但有时会卡在guard let Here is the code:这是代码:

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

} }

It seems to get stuck at the guard let in centerMapOnUserLocation() .它似乎卡在了centerMapOnUserLocation()的守卫上。 This is shown through print statements:这通过打印语句显示:

Authorization changed in locationManager(_:didChangeAuthorization:). locationManager(_:didChangeAuthorization:) 中的授权已更改。 Calling centerMapOnUserLocation呼叫中心MapOnUserLocation

In centerMapOnUserLocation()centerMapOnUserLocation()

Error getting coordinate获取坐标时出错

Im not sure how to fix this.我不知道如何解决这个问题。 Like I said sometimes it passes by the guard let and sometimes it gets stuck.就像我说的,有时它会经过警卫让,有时它会卡住。

In you viewDidLoad add this line:在你viewDidLoad添加这一行:

locationManager.startUpdatingLocation()

Then use this CLLocationManagerDelegate method:然后使用这个CLLocationManagerDelegate方法:

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

You could pass in the locations into your method and move guard let before passing the location like this:您可以将位置传递到您的方法中并在传递位置之前移动guard let ,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM