2012-04-02 48 views
0

我正在使用位置管理器来获取用户位置时,他/她按下按钮。CLLocationManager奇怪的行为

我只需要那个exat时间的位置,所以我得到位置后关闭更新。

事情,如果我在第一次获得id 0 lat 0 lng的位置。

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 
    lat = newLocation.coordinate.latitude; 
    lng = newLocation.coordinate.longitude; 
    [locationManager stopUpdatingLocation]; 
    NSLog(@"New Latlng: %f x %f", lat, lng); 
} 

当用户按下按钮时,我调用:[locationManager startUpdatingLocation];

然后,我将位置发送到我的服务器[self sendData]。但是位置是零。 在我-sendData方法我增加了一个NSLog的追查发生了什么事情,我意识到,我是在数据发送到-locationManager之前的服务器:didUpdateToLocation被调用......

2012-04-02 16:06:24.225 MyApp[2892:707] ---- Data sent to server ---- 
2012-04-02 16:06:25.167 MyApp[2892:707] Nova Latlng: -23.003582 x -43.316311 

我想这但它没有按预期工作:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 
    [locationManager startUpdatingLocation]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self sendData]; 
    }); 
}); 

如何使[self sendData]等待,直到我有lat和lng变量正确填充?

回答

0

为什么不让你打电话stopUpdatingLocation

+0

该委托仍然被调用至少2次。 – cleverbit 2012-10-11 20:42:08

0

把这段代码

dispatch_async(dispatch_get_main_queue(), ^{ 
    [self sendData]; 
}); 
didUpdateToLocation:

[locationManager stopUpdatingLocation]; 

应该这样做。位置管理器更新是异步的,所以在尝试对数据执行任何操作之前,您必须等待有些事情需要处理。

+0

通过这样做,sendData方法被调用3次...你知道为什么吗? – 2012-04-02 20:31:21

+0

在停止更新的代码行被调用一次之前,可能会多次调用“didUpdateToLocation:”。为该方法添加一个静态布尔值,以便您可以知道是否发送了一次数据,并且只在布尔为NO时才发送。 – 2012-04-02 20:33:41