应用程序处于后台时,将CLLocation保存到CoreData

时间:2016-07-29 13:01:58

标签: ios objective-c iphone core-data cllocationmanager

我发现了其他问题的多个相似之处,但我真的没有找到任何有用的答案来回答我的问题。 我的Sport-Tracker iOS应用程序甚至可以在后台跟踪位置。每50个位置,我会将CLLocation的数组保存到CoreData的SportActivity中。但是如果使用代码保存我的应用程序在后台:

NSError *error;
if (![_managedObjectContext save:&error])
    NSLog(@"Error saving data: %@", [error localizedDescription]);

我的_managedObjectContext被引用如下:

- (NSManagedObjectContext *)managedObjectContext
{
 if (_managedObjectContext != nil) {
    return _managedObjectContext;
 }
 NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
 if (coordinator != nil) {
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
 }
 return _managedObjectContext;
}

我可以在日志中看到此错误:

Can't endBackgroundTask: no background task exists with identifier a3,
or it may have already been ended.
Break in UIApplicationEndBackgroundTaskError() to debug.

为了在我的应用程序上保存数据,我添加了

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

位置(我的CoreData对象包含坐标)到NSMutableArray。当Array计算50个元素时,我调用CoreData

的保存实例
for (CLLocation *location in _locations) {
    Location *locationObject = [[CoreDataManager sharedInstance] newLocationForActivity:_currentActivity];

    locationObject.timestamp = [NSDate new];
    locationObject.latitude = location.coordinate.latitude;
    locationObject.longitude = location.coordinate.longitude;
    locationObject.altitude = location.altitude;
    [locationArray addObject:locationObject];
}

0 个答案:

没有答案