2

我正在尝试大约每 5 分钟向我们的服务器发送 GPS 数据信息,无论应用程序是否正在运行或是否在后台。我可以让它运行,但它似乎一直在运行。我设置了一个计时器,每 10 秒发送一次以进行测试,但它只是继续发送。我不认为这是错误的计时器,我相信 locationManager 没有停止,我不知道为什么。

这是我的代码

- (void)applicationDidEnterBackground:(UIApplication *)application
{

NSLog(@"Went to Background");

UIApplication *app = [UIApplication sharedApplication];

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

[self.locationManager startUpdatingLocation];
self.timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self.locationManager selector:@selector(startUpdatingLocation) userInfo:nil repeats:YES];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;

[self.locationManager startUpdatingLocation];

[NSTimer scheduledTimerWithTimeInterval:10 target:self.locationManager selector:@selector(startUpdatingLocation) userInfo:nil repeats:YES];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (newLocation.horizontalAccuracy <= 100.0f) {
    // Use json and send data to server
    ...
    ...

    [self.locationManager stopUpdatingLocation];
    self.locationManager = nil;
    self.locationManager.delegate = nil;
}
}

无论是在后台还是前台,它都会做同样的事情。我还需要做些什么来阻止 locationManager 更新吗?

4

1 回答 1

3

要定期将位置发送到服务器,您希望存储和比较接收更新的日期,不要使用计时器,因为当应用程序在后台时它们是不可靠的。

@implementation
{
    NSDate* _lastSentUpdateAt;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    NSLog(@"Went to Background");
    // Update in 5 minutes.
    _lastSentUpdateAt = [NSDate date];
    [self.locationManager startUpdatingLocation];
}
// ...

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    // Accuracy is good & 5 minutes have passed.
    if (newLocation.horizontalAccuracy <= 100.0f && [_lastSentUpdateAt timeIntervalSinceNow] < -5 * 60) {
        // Set date to now
        _lastSentUpdateAt = [NSDate date];

        // Use json and send data to server
        ...
        ...
    }
}
@end
于 2013-09-16T13:50:41.590 回答