如何检查locationManager是否更新了当前位置?

时间:2017-04-03 05:48:11

标签: ios swift mapkit

我想在启动时显示用户的当前位置,然后继续跟踪他们的位置,但不要以当前位置为中心。我的想法是以viewDidLoad()中的当前位置为中心,但我不知道如何在居中之前等待locationManager更新当前位置。以下是我的代码的相关部分:

var currentLocation : CLLocation?
@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

        // wait for currentLocation to be updated
        animateMap(currentLocation!)

    }

    mapView.showsUserLocation = true
}

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

func animateMap(_ location: CLLocation) {
    let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 1000, 1000)
    mapView.setRegion(region, animated: true)
}

3 个答案:

答案 0 :(得分:0)

// MARK: - 位置lattitude longtitude方法委托方法

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    if locationManager.location != nil
    {
        let locValue = (locationManager.location?.coordinate)!
        lat = locValue.latitude
        long = locValue.longitude
    }
}

答案 1 :(得分:0)

您只需在初始化animateMap(currentLocation!)的委托方法didUpdateLocations中调用currentLocation函数。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations.last!
    animateMap(currentLocation!)
    //Either Call `stop​Updating​Location()`
    locationManager.stop​Updating​Location()
    //Or you can create one boolean property with default value false and compare it inside this method
    if !animatedFlag {
        animateMap(currentLocation!)
        animatedFlag = true
    }
}

var animatedFlag = false

答案 2 :(得分:0)

在didUpdateLocations委托方法中调用animateMap函数,而不是在viewDidLoad中调用。并且,允许地图仅在第一次居中。你可以为它做一些bool变量。

var isLocationUpdated = false 

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations.last!
    if (!isLocationUpdated)
     {
        animateMap(currentLocation!)
        isLocationUpdated = true
     }
}