【问题标题】:Inconsistent locationManager didupdatetolocation on Iphone不一致的位置管理器没有更新到 Iphone 上的位置
【发布时间】:2023-12-22 08:30:01
【问题描述】:
@implementation MyLocation


SYNTHESIZE_SINGLETON_FOR_CLASS(MyLocation);

@synthesize delegate, locationManager;

- (id) init 
{
    self = [super init];
    if (self != nil) 
    {       
        self.locationManager = [[[CLLocationManager alloc] init] autorelease];

        self.locationManager.delegate = self;
    }
    return self;
}


- (void) timeoutHandler:(NSTimer *)_timer
{

    timer = nil;

    [self update_location];
}

-(void) update_location
{
    hasLocation=NO;

    [locationManager startUpdatingLocation];

    timer = [NSTimer scheduledTimerWithTimeInterval: 3.0
                                         target: self
                                       selector: @selector(timeoutHandler:)
                                       userInfo: nil
                                        repeats: NO
         ];
}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"location ready");
    if(timer != nil) {
        [timer invalidate];
        timer = nil;
    }
    hasLocation = YES;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"location_ready"                         object:nil]; 


    if (debug_switch)
        NSLog(@" Delegate function, Getting new location from locationManager from Mylocation.m");


    _coordinate = newLocation.coordinate;

    source_lat=_coordinate.latitude;
    source_lng=_coordinate.longitude;

    //TRACE(@"new location: %f %f", _coordinate.latitude, _coordinate.longitude);
    //[delegate locationUpdate:newLocation.coordinate];

}

第一次运行update_location例程,位置管理器快速跳转到didupdatetolocation的回调例程。没问题

但是,下次我再次调用 update_location 函数时,回调 didupdatetolocation 从未进入。为什么会有这样的差异?为什么没有输入回调?

【问题讨论】:

    标签: iphone cllocationmanager


    【解决方案1】:

    您对 LocationManager 的使用不正确。只需调用一次startUpdatingLocation,只要有足够大的变化,就会重复调用回调。

    根据您的观察,可能调用回调没有显着变化。

    【讨论】:

    • 好的,如果我不更改我的位置,是否会再次调用该回调?
    • 在位置改变之前不会调用回调。有时尤其是在建筑物内,但那是由于 GPS 信号本身的波动(所以回调会给你改变位置)。
    • 而且,即使您没有更改位置,也会在调用 startUpdatingLocation 之后立即调用回调。我认为在您的原始代码中,第二次和以后的 startUpdatingLocation 调用被简单地忽略了。 (这是我最好的猜测,我没有尝试多次调用 startUpdatingLocation。)
    【解决方案2】:

    为什么要创建一个不断调用 CLLocationManager startUpdatingLocation 的计时器?

    CLLocationManager 通常通过将自己设置为委托来使用。启动它,然后当位置更改时您会收到回调。

    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
    

    这是一个展示如何使用它的教程:

    http://mobileorchard.com/hello-there-a-corelocation-tutorial/

    【讨论】: