我正在編寫一個代碼來不斷跟蹤應用CoreLocation
的用戶。由於我無法始終保持GPS,因此我在AppDelegate
中使用StartMonitoringSignificantLocationChange
來檢測到重大變化。我在UIBackgroundMode
中註冊了location
。 in didUpdateLocations
方法,我檢查從以前記錄的位置的當前距離。如果它很重要,我申請StopMonitoringSignificantLocationChange
和StartUpdatingLocation
以獲得準確的位置。同時我啓動計時器(30秒)以查看用戶是靜止還是移動。如果用戶不再移動,我再次應用StopUpdatingLocation
和StartMonitoringSignificantLocationChange
。 我也以我的AppDelegate: -(void)applicationWillResignActive:(UIApplication *)application
定義的後臺任務如下:在iOS 7後臺模式下高效跟蹤用戶的問題
- (void)applicationWillResignActive:(UIApplication *)application
{
if (![[GeoSampleManager sharedManager] isLiveTracking])
{
GeoSampleManager *manager = [HTSGeoSampleManager sharedManager];
[manager.locationManager stopMonitoringSignificantLocationChanges];
self.bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:self.bgTask];
self.bgTask = UIBackgroundTaskInvalid;
}];
[manager.locationManager startMonitoringSignificantLocationChanges];
}
}
我關閉後臺任務時,應用程序eneters前景:
- (void)applicationDidBecomeActive:(UIApplication *)application
{
if(self.bgTask != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
self.bgTask = UIBackgroundTaskInvalid;
}
}
這裏是我的didUpdateLocations
方法:
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
CLLocation* newLocation = [locations lastObject];
if(self.isLiveTracking)
{
//Test that the horizontal accuracy does not indicate an invalid measurement
if (newLocation.horizontalAccuracy < 0 || newLocation.horizontalAccuracy > 200)
{
return;
}
if([self.lastLocation distanceFromLocation:newLocation] > 0)
{
//Create and save a GeoSample
[GeoSampleManager createSampleForLocation:newLocation onTrip:self.activeTrip];
self.lastLocation = newLocation;
}
}
else
{
if([self.lastLocation distanceFromLocation:newLocation] > 0)
{
[self.locationManager stopMonitoringSignificantLocationChanges];
self.idleChecker = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(checkIdle:) userInfo:nil repeats:YES];
[self.locationManager startUpdatingLocation];
self.isLiveTracking = YES;
}
}
}
最後這裏是定時器方法:
- (void)checkIdle:(NSTimer*)timer
{
if(abs([self.lastLocation.timestamp timeIntervalSinceNow]) >= 30.0)
{
//Stopping the idle-time checking timer
[self.idleChecker invalidate];
self.idleChecker = nil;
[self.locationManager stopUpdatingLocation];
[self.locationManager startMonitoringSignificantLocationChanges];
self.isLiveTracking = NO;
}
}
但是,該應用程序被暫停(有時在5-10秒後,有時在10分鐘後),並停止接收位置更新。由於我在這個問題上掙扎了一個多月,而且我嘗試了幾乎所有可能的解決方案,我非常感謝你能以任何方式幫助我解決問題。
乾杯
你曾經從應用程序切換器中刪除應用程序嗎? – sangony
不,它只是在鎖定屏幕時發送到背景。 – Behrang
看看以前的帖子。它可能會給你一個想法(看所有的答案)。 http://stackoverflow.com/questions/18946881/background-location-services-not-working-in-ios-7 – sangony