简体   繁体   English

CLLocationManager奇怪的行为

[英]CLLocationManager strange behavior

I am using location manager to get user location when he/she presses a button. 我正在使用位置管理器来在用户按下按钮时获取用户位置。

I just need that exat time location, so I turn off the updates after I get the location. 我只需要该exat time位置,因此在获得该位置后,我将关闭更新。

The thing if that the location I am getting id 0 lat 0 lng at the first time. 如果该位置是我第一次获得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);
}

When the user presses the button I call: [locationManager startUpdatingLocation]; 当用户按下按钮时,我将调用:[locationManager startUpdatingLocation];

And right after that I send the location to my server [self sendData]. 然后,我将位置发送到服务器[self sendData]。 But the location is zero. 但是位置为零。 At my -sendData method I added an NSLog to track down what was going on and I realized that I was sending the data to the server before the -locationManager:didUpdateToLocation gets called... 在我的-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

I tried this but it didnt work as expected either: 我尝试了这个,但是它还是没有按预期工作:

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

How to make the [self sendData] wait until I have the lat and lng variables properly filled? 如何使[self sendData]等到正确填入lat和lng变量后,该如何处理?

为什么您在stopUpdatingLocation之后不stopUpdatingLocation拨打该电话?

Put this code 输入此代码

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

in didUpdateToLocation: after didUpdateToLocation:之后

[locationManager stopUpdatingLocation];

That should do it. 那应该做。 The Location Manager updates come asynchronously, so you have to wait until there is something to process before you try to do anything with the data. 位置管理器更新是异步进行的,因此您必须等到要处理的内容之后才能尝试对数据进行任何处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM