I'm trying to save data into core data after the completion of a web request.
In AppDelegate
I have my context. In the following the code for get the context:
- (NSManagedObjectContext *)contex {
@synchronized(self) {
if (_contex == nil) {
_contex = [[NSManagedObjectContext alloc] init];
[_contex setPersistentStoreCoordinator:self.persistentStoreCoordinator];
}
return _contex;
}
}
Like the Apple guidelines say, I have one persistent store coordinata shared with multiple contexts.
This is the code where I take the data from web, get the context and make the call to the method for save the new value into core data.
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *localFile, NSURLResponse *response, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIImage *image;
if (!error) {
NSData *imageData = [NSData dataWithContentsOfURL:localFile];
image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"thumbnailIsSetted" object:self userInfo:@{@"image": image,
@"PhotoUrl": photo.url}];
@synchronized(self) {
NSManagedObjectContext *context = [(SocialMapAppDelegate *)[[UIApplication sharedApplication] delegate] contex];
[Photo addThumbnailData:imageData toPicture:photo.url fromContext:context];
}
});
} else {
//if we get an error, we send the default icon
image = [UIImage imageNamed:@"Photo-thumbnail"];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"thumbnailIsSetted" object:self userInfo:@{@"cached image": image,
@"PhotoUrl": photo.url}];
});
}
}];
[task resume]; //we resume the task in case it is souspended
}];
and this is the method that I use for save the data into core data:
+ (void)addThumbnailData:(NSData *)data toPicture:(NSString *)pictureUrl fromContext:(NSManagedObjectContext *)context
{
if (pictureUrl && context) {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photo"];
request.predicate = [NSPredicate predicateWithFormat:@"url == %@",pictureUrl];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if ([matches count] == 1) {
Photo *photo = [matches lastObject];
photo.thumbnailData = data;
if (![context save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
}
}
}
I can't figure where is the problem, the context is not nil, and I don't get any error. If i restart the app the data are there.