0

我正在 iOS 上创建一个可以跟踪设备位置的应用程序。为了检查设备的位置是否是最近的,我使用以下代码来比较位置的时间戳和当前时间。

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
NSLog(@"%f",howRecent);
}

但是,这样做的问题是,如果设备在一个位置静止不动,则不会调用代理并且时间间隔会不断增加。因此,我想知道是否有更好的方法通过强制刷新位置更新来检索位置的年龄。

4

1 回答 1

0

您可以使用 NSTimer 刷新它

- (void)viewDidLoad
{
    [self setLastActivityTime:[NSDate date]];
    [self setStatusTimer:[NSTimer timerWithTimeInterval:0.25 target:self selector:@selector(updateStatus:) userInfo:nil repeats:YES]];
    [[NSRunLoop currentRunLoop] addTimer:[self statusTimer] forMode:[self runLoopMode]];
}

- (void)updateStatus:(NSTimer*)timer
{
    [locationmanager startUpdatingLocation]; // this will call didUpdateLocations delegate

    if (![self inProgress]) {
        [self setStatusTimer:nil];
    }
}
- (void)setStatusTimer:(NSTimer *)timer
{
    [self retain];
    // We must invalidate the old timer here, not before we've created and scheduled a new timer
    // This is because the timer may be the only thing retaining an asynchronous request
    if (statusTimer && timer != statusTimer) {
        [statusTimer invalidate];
        [statusTimer release];
    }
    statusTimer = [timer retain];
    [self release];
}

我希望它会帮助你。

于 2013-09-27T08:12:58.757 回答