使用 iOS 每 x 分钟发送一次 GPS 坐标 - 核心位置不会停止更新



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

这是我的代码

- (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;
}
}

无论是在背景还是前景中,它都会做同样的事情。我还需要做些什么来阻止位置管理器更新吗?

若要定期将位置发送到服务器,您需要存储和比较收到更新的日期,请不要使用计时器,因为当应用程序在后台运行时,计时器不可靠。

@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

最新更新