Getlocation function incorrectly locates
My code is to return the location of the device to place the pin.
For some reason, when it is called multiple times, it always returns the value returned on the first call.
Fingerprints in the code return the first value. I probably don't notice anything obvious, but I can't figure out what.
func getLocation ()-> CLLocation! {
locationManager.startUpdatingLocation()
var x = locationManager.location
println(x.coordinate.latitude)
println(x.coordinate.longitude)
return x
}
source to share
The problem is that the location manager doesn't work that way. startUpdatingLocation()
does not change the state of the location manager. Instead, he calls you in the method of the delegate locationManager:didUpdateLocations:
. You have to set up a delegate and implement a delegate that delegates to the method and that is where you will get your location.
The actual code example is here: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch22p773location/ch35p1032location/ViewController.swift
Please note that in this code, like you, I just need one place. But the location manager will keep calling the delegate method forever until I stop it, so I have to stop it as well. However, I cannot stop it immediately after one call, because the delegate method gets called multiple times before I get a good seat. I keep checking the horizontal precision and the elapsed time and I stop the location manager when I get a good enough location or too much time has passed (maybe we are indoors and can't get good precision).
source to share