在 viewDidLoad 中获取位置

Getting Location in viewDidLoad

我正在尝试获取用户位置,但在加载视图时它不起作用。我有一个刷新方法,效果很好,但需要用户点击刷新按钮。当视图加载时,用户位置出现在地图上,但在 getLocation() 中,myLocation 为 nil。再一次,点击调用 refreshLocation() 的刷新按钮按预期工作。

override func viewDidLoad() {
        super.viewDidLoad()

        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer

        mapView.userTrackingMode = .follow

        getLocationAuthorizationStatus()
    }

请求授权

func getLocationAuthorizationStatus() {
        print("getLocationAuthorizationStatus()")
        if CLLocationManager.authorizationStatus() == .notDetermined {
            locationManager.requestWhenInUseAuthorization()
        } else if CLLocationManager.authorizationStatus() == .denied {
            // Display UIAlertController
            let locationDeniedAlert = BasicAlert(title: "", message: "Location services were denied. Please enable location services in Settings.", preferredStyle: .alert)

            let settingsAction = UIAlertAction(title: "Settings", style: .default, handler: {
                (action) -> Void in
                let settingsURL = URL(string: UIApplicationOpenSettingsURLString)
                if let url = settingsURL {
                    // UIApplication.shared.openURL(url)
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }

                locationDeniedAlert.dismiss(animated: true, completion: nil)
            })

            locationDeniedAlert.addAction(settingsAction)

            self.present(locationDeniedAlert, animated: true, completion: nil)

        } else if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
            if fromSearch {
                fromSearch = false
            } else {
                getLocation()
            }
        }
    }

获取位置

func getLocation() {
        print("getLocation()")
        locationManager.startUpdatingLocation()

        if locationManager.location != nil {
            myLocation = locationManager.location!
            if mapView.annotations.count == 1 && mapView.annotations[0] as! MKUserLocation == mapView.userLocation {
                retrieveGymsWithLocation()
            }
        } else {
            myLocation = nil
            print("location = nil")
        }
    }

    @objc func refreshLocation() {
        print("refreshLocation()")
        let annotationsToRemove = mapView.annotations
        mapView.removeAnnotations(annotationsToRemove)
        gyms.removeAll()
        imageArrays.removeAll()
        gymLocations.removeAll()

        getLocationAuthorizationStatus()
    }

位置管理器

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

CLLocationManager 需要一段时间才能确定当前位置,具体取决于 gps 卫星可用性和其他各种影响。因此,您只需稍等片刻,直到位置 属性 设置完毕。 您通常会在委托方法中执行此操作:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    manager.stopUpdatingLocation()
    myLocation = locations.last

    if mapView.annotations.count == 1 && mapView.annotations[0] as! MKUserLocation == mapView.userLocation {
        retrieveGymsWithLocation()
    } 
}