我知道如何用 NSTimer 来做这个,但我不想每隔几秒就获得当前的 iPhone 坐标。我不能使用计时器,因为我在应用程序处于后台时获取坐标。
我已经尝试了一些东西,但这每秒调用一次,而不是每 10 秒调用一次,因为我不想这样做。
我在这里做错了什么?
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *loc = [locations objectAtIndex:0];
NSDate* eventDate = loc.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (howRecent < 10)
{
CLLocation* location = [locations lastObject];
double lat = location.coordinate.latitude;
double lng = location.coordinate.longitude;
NSLog(@"lat:%f lng:%f", lat, lng);
首先尝试每 10 秒执行一次后台任务,但如果我在这里做任何事情,不知道在哪里设置时间:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
backgroundTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTask != UIBackgroundTaskInvalid)
{
[application endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_pendingLocationsTimer = [NSTimer timerWithTimeInterval:_pendingLocationsTimerDuration
target:self
selector:@selector(_acceptBestAvailableLocation:)
userInfo:nil repeats:NO];
NSRunLoop *loop = [NSRunLoop currentRunLoop];
[loop addTimer:_pendingLocationsTimer forMode:NSRunLoopCommonModes];
[loop run];
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTask != UIBackgroundTaskInvalid)
{
// if you don't call endBackgroundTask, the OS will exit your app.
[application endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}
});
});
}