在viewDidLoad中获取位置

时间:2018-01-16 14:52:16

标签: ios swift cllocationmanager

我正在尝试获取用户位置,但在视图加载时它不起作用。我有一个很好的刷新方法,但需要用户点击刷新按钮。视图加载时,用户位置显示在地图上,但在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
    }

1 个答案:

答案 0 :(得分:1)

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