【发布时间】:2015-05-24 19:10:49
【问题描述】:
我有一个应用程序,我想在 viewDidLoad 中获取用户位置,然后我将 lat 和 long 存储在变量中,并在函数中使用它们来根据用户的位置获取数据。我有一个计时器,它每 x 分钟调用一个函数来获取数据(我们称之为 getData()),第一次调用 getData() 时,lat 和 long 为 0,但第二次、第三次等等。他们有价值观。
当我在模拟器中更新坐标(在运行时)时,我确实得到了 lat 和 long 的更新值,但它是第一次运行时 lat 和 long 始终为 0。我的代码如下所示:
let locationManager = CLLocationManager()
var getDataGroup = dispatch_group_create()
override func viewDidLoad() {
super.viewDidLoad()
dispatch_group_enter(getDataGroup)
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
dispatch_group_leave(getDataGroup)
dispatch_group_wait(getDataGroup, DISPATCH_TIME_FOREVER)
dispatch_async(dispatch_get_main_queue()) {
self.getData()
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
if (error != nil){
println("Error: " + error.localizedDescription)
return
}
if (placemarks.count > 0){
let pm = placemarks[0] as! CLPlacemark
self.displayLocationInfo(pm)
}
else{
println("Error with location data")
}
})
}
func displayLocationInfo (placemark : CLPlacemark){
self.locationManager.stopUpdatingLocation()
lat = String(stringInterpolationSegment: placemark.location.coordinate.latitude)
long = String(stringInterpolationSegment: placemark.location.coordinate.longitude)
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error: " + error.localizedDescription)
}
func getData(){
// Do stuff with lat and long...
}
由于某种原因,第一次运行 lat 和 long 都是 0,其余运行它们具有有效值。问题是 getData 在 locationManager 和 displayLocationInfo 方法之前被调用,即使我出于某种原因在调用 getData() 之前添加了 self.locationManager.startUpdatingLocation()。
【问题讨论】:
-
什么时候调用 getData()?听起来您是在第一次收到对 didUpdateLocations 的回调之前调用它。在 GetData 和 didUpdateLocations 中放置一个断点,看看哪个先触发。
-
@KevinS 它只在 viewDidLoad 中调用,然后在计时器函数中调用。 getData 首先触发。定时器函数在 viewDidAppear 函数中。
标签: ios multithreading swift cllocationmanager