2015-05-19 30 views
0

我在CLLocationManager調用startUpdatingLocation(),並在didUpdateLocations方法我打電話stopUpdatingLocation()時精度小於100um,像這樣:CLLocationManager忽略stopUpdatingLocation

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { 
    var lastLocation: CLLocation = locations.last! as! CLLocation 
    var accuracy = lastLocation.horizontalAccuracy 

    if (accuracy < 100) { 
     locationCoordinate = lastLocation.coordinate 
     locationManager.stopUpdatingLocation() 
     getData() 
    } 
} 

然而,didUpdateLocations方法仍稱一個或除非我將locationManager設置爲nil,否則在致電stopUpdatingLocations()後再多兩次。很顯然,這也會多次調用我的方法getData(),這是我不想要的。如何在不將其設置爲nil的情況下停止locationManager

+3

它是一種常見的事解決了這個問題。只要使用一個bool成員變量來防止不應該調用getData()。 – Gruntcakes

回答

0

就像H先生所說的那樣,只要使用一個bool即可。

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { 
    var lastLocation: CLLocation = locations.last! as! CLLocation 
    var accuracy = lastLocation.horizontalAccuracy 

    static bool flag = NO; //Or however this is done in Swift) 

    if (accuracy < 100 && !flag) { //Check the flag in the condition 

     locationCoordinate = lastLocation.coordinate 
     locationManager.stopUpdatingLocation() 
     getData() 

     flag = YES; //Set flag to yes here 

    } 
} 
5

我也面臨類似的issue.I通過CLLocationManagerDelegate設置爲零

+0

這就是答案! –