我正在尝试大约每 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 更新吗?