问题
My code is supposed to return the location of the device, for the purposes of placing a pin.
For some reason when it is called multiple times, it always returns the value returned the first time it was called.
The prints in the code are returning the first value. I am probably overlooking something obvious, but I cannot figure out what.
func getLocation ()-> CLLocation! {
locationManager.startUpdatingLocation()
var x = locationManager.location
println(x.coordinate.latitude)
println(x.coordinate.longitude)
return x
}
回答1:
The problem is that this is not how location manager works. startUpdatingLocation()
does not immediately change the state of the location manager. Instead, it calls you back in a delegate method, locationManager:didUpdateLocations:
. You must set a delegate and implement the delegate that delegate method, and that is where you receive your location.
Actual example code here: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch22p773location/ch35p1032location/ViewController.swift
Note that in that code, like you, I just want one location. But the location manager will keep calling the delegate method forever until I stop it, so I also have to stop it. However, I can't stop it immediately, after just one call, because the delegate method is called several times before I get a good location. I keep checking the horizontal accuracy and the time elapsed, and I stop the location manager when I get a good enough location or too much time has elapsed (perhaps we are indoors and cannot get good accuracy).
来源:https://stackoverflow.com/questions/30037667/getlocation-function-not-properly-finding-location