How To Extract String Reference To An Image In iOS And Then Load The Image Later?

Umar Ashfaq
Eastros
Published in
2 min readApr 30, 2014

Recently I had to create this flow in one of my projects:

  1. Let the user select an image from the gallery.
  2. Store the image reference to Core Data.
  3. Later, load the image from the gallery using the saved reference and show image again to the user.

Here is how I did the job:

How To Let User Select An Image From Gallery?

Imagine you have controller MyDummyController which shows a button “Pick An Image”. You’d like to open phone Gallery when that button is tapped. First make sure that your controller implements UIImagePickerControllerDelegate.

[sourcecode language=”objc”]
@interface MyDummyController : UIViewController<UIImagePickerControllerDelegate>
[/sourcecode]

Next, implement following methods in your implementation file.

[sourcecode language=”objc”]
// make sure this method is invoked when you tap “Pick An Image” button
-(void)onTapPickAnImage
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:imagePicker animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// here is the image user selected
UIImage *image = [info objectForKey:@”UIImagePickerControllerOriginalImage”];

// here is the URL to the image
NSURL *url = [info objectForKey:@”UIImagePickerControllerReferenceURL”];
}
[/sourcecode]

How To Extract String Reference From The Image URL?

In different persistence systems, for example Core Data, you cannot save an NSURL directly. Which means, if you want to store reference of selected image somewhere, you’ll need it in a string. It can be done like below:
[sourcecode language=”objc”]
NSURL *url = [info objectForKey:@”UIImagePickerControllerReferenceURL”];
NSString *ref = url.absoluteString;
// now you can persist your string reference somewhere
[/sourcecode]

How To Load Image Again Using String Reference?

[sourcecode language=”objc”]
// here we are loading the string reference to image we want to load
NSString *ref = [self loadMyImageRef]; // loadMyImageRef is a dummy method, you can put your implementation here

// ALAssetsLibrary provides a way to access photos/videos in gallery programmatically
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:[NSURL URLWithString:ref] resultBlock:^(ALAsset *asset) {
// here we have received the image data, now you can easily display it wherever you like
UIImage *image = [UIImage imageWithCGImage:asset.defaultRepresentation.fullResolutionImage];
NSLog(@”Image loaded successfully!”);
} failureBlock:^(NSError *error) {
NSLog(@”An error occurred while loading image: %@”, error.description);
}];
[/sourcecode]

--

--