简体   繁体   English

在viewDidLoad中获取位置

[英]Getting Location in viewDidLoad

I am trying to get the user location but it doesn't work when the view loads. 我正在尝试获取用户位置,但是在加载视图时它不起作用。 I have a refresh method that works just fine but that requires the user to tap a refresh button. 我有一种刷新方法,该方法工作得很好,但是需要用户点击刷新按钮。 The user location appears on the map when the view loads but in getLocation(), myLocation is nil. 加载视图时,用户位置会显示在地图上,但在getLocation()中,myLocation为nil。 And again, tapping the refresh button that calls refreshLocation() works as expected. 再次,点击调用refreshLocation()的刷新按钮可以正常工作。

override func viewDidLoad() {
        super.viewDidLoad()

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

        mapView.userTrackingMode = .follow

        getLocationAuthorizationStatus()
    }

Request Authorization 请求授权

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

Get Location 取得位置

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

Location Manager 位置经理

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

It takes a while for CLLocationManager to determine the current location, depending on gps satellite availability and other kinds of influence. CLLocationManager需要一段时间才能确定当前位置,具体取决于gps卫星的可用性和其他影响。 Therefore, you'll simply have to wait a while until the location property is set. 因此,您只需要稍等一会儿,直到设置了location属性。 You typically would do this in the delegate method: 通常,您可以在委托方法中执行此操作:

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

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

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