Ios 获取viewDidLoad中的位置

Ios 获取viewDidLoad中的位置,ios,swift,cllocationmanager,Ios,Swift,Cllocationmanager,我正在尝试获取用户位置,但在加载视图时它不起作用。我有一个刷新方法,工作得很好,但需要用户点击刷新按钮。加载视图时,用户位置显示在地图上,但在getLocation中,myLocation为零。同样,点击调用refreshLocation的refresh按钮也能正常工作 override func viewDidLoad() { super.viewDidLoad() locationManager = CLLocationManager() l

我正在尝试获取用户位置,但在加载视图时它不起作用。我有一个刷新方法,工作得很好,但需要用户点击刷新按钮。加载视图时,用户位置显示在地图上,但在getLocation中,myLocation为零。同样,点击调用refreshLocation的refresh按钮也能正常工作

override func viewDidLoad() {
        super.viewDidLoad()

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

        mapView.userTrackingMode = .follow

        getLocationAuthorizationStatus()
    }
请求授权

获取位置

位置管理器

CLLocationManager需要一段时间来确定当前位置,这取决于gps卫星可用性和其他类型的影响。因此,您只需等待一段时间,直到设置location属性。 您通常会在委托方法中执行此操作:

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