Reputation: 1093
Can anyone explain, why the delegated method 'CLLocationManager(didUpdateLocations)' is called for 4 times although I immediately stop updating? I need the current location only once :)
import UIKit
import MapKit
class ContactView: UIViewController, CLLocationManagerDelegate {
let clLocationManager = CLLocationManager()
var latitude: AnyObject = 0.000000
var longitude: AnyObject = 0.000000
override func viewDidLoad() {
super.viewDidLoad()
self.nameTextField.delegate = self
clLocationManager.delegate = self
clLocationManager.desiredAccuracy = kCLLocationAccuracyBest
clLocationManager.requestWhenInUseAuthorization()
clLocationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {
(placemarks, error) -> Void in
self.clLocationManager.stopUpdatingLocation()
if placemarks!.count > 0 {
self.latitude = (manager.location?.coordinate.latitude)!
self.longitude = (manager.location?.coordinate.longitude)!
print(self.latitude)
print(self.longitude)
} else {
print("Error")
}
})
}
}
Thanks!
Upvotes: 3
Views: 633
Reputation: 8200
You need to change your code like the following:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
manager.stopUpdatingLocation()
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {
(placemarks, error) -> Void in
if placemarks!.count > 0 {
self.latitude = (manager.location?.coordinate.latitude)!
self.longitude = (manager.location?.coordinate.longitude)!
print(self.latitude)
print(self.longitude)
} else {
print("Error")
}
})
}
You're seeing the problem because you're continuing to update your location while the call to reverse geocode your location is still happening.
Upvotes: 1
Reputation: 6150
Try to move the stopUpdatingLocation outside from reverseGeocodeLocation
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
manager.stopUpdatingLocation()
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {
(placemarks, error) -> Void in
if placemarks!.count > 0 {
self.latitude = (manager.location?.coordinate.latitude)!
self.longitude = (manager.location?.coordinate.longitude)!
print(self.latitude)
print(self.longitude)
} else {
print("Error")
}
})
}
}
Upvotes: 2