How to saving reference (image URL or path) of images in core data and load it later when needed?

StackOverflow https://stackoverflow.com/questions/20308511

  •  06-08-2022
  •  | 
  •  

Question

I am working on an application where I need to take photo and video from the device camera and show it in a collection view. The application save the images and videos in camera roll so I need to save a reference of those asset in coredata so that teh app can load it later.

I am using regular functions like,

writeImageToSavedPhotosAlbum:[cameraMedia CGImage]
                             metadata:metaData
                             completionBlock:^(NSURL *assetURL,NSError *error)

and

writeVideoAtPathToSavedPhotosAlbum:mediaUrl
                           completionBlock:^(NSURL *assetURL, NSError *error)

where i get the assetURL easily. But I am not sure if i can save the assetURL directly in coredata and if not, what should i do to save the image reference and efficiently reload it from the save reference later?

Just to clarify my question, I know how to use core data. My question is what should I save in the core data as the image/video reference? for example, assetURL is NSURL object and probably i cannot save it as String in coredata. So, is there any way to convert the URL and save it to coredata. Later how can I load the image from the reference saved in coredata?

Was it helpful?

Solution

Here is how to get the Asset URL:

[yourAssetsLibrary  writeImageToSavedPhotosAlbum:[cameraMedia CGImage]
                                        metadata:metaData
                                 completionBlock:^(NSURL *assetURL, NSError *error) {    
                                      NSLog(@"%@", assetURL);// this what you need to save    
                              }];

Save in core data:

NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[fetchedResultsController fetchRequest] entity];
YOURENTITY *yourEntity = (YOURENTITY *) [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[yourEntity setValue:assetURL forKey:@"imagePath"];// save it here

NSError *error;
if (![context save:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top