iOS: Save an Image in Camera Roll

Saving an image to the camera roll on the iPhone is as close as a method call in the UIKit. However, it takes a few steps to wrap together code to manage error handling and notification that the image has been saved. Let’s see how this works.

Let’s begin with the method description to save an image:

  void UIImageWriteToSavedPhotosAlbum(UIImage *image, 
                  id completionTarget, SEL completionSelector, void *contextInfo);

completionTarget refers to the object in which the completionSelector can be found. In other words, what object has the method that will be called once the file write is complete?contextInfo is a void * that you can use to specify content to be passed to thecompletionSelector.

Obviously, the image is a required paramater. The other three are only needed if you prefer to be notified asynchronously when the write is complete. Here’s how a call to the above method might look:

  // Image to save
  UIImage *img = [UIImage imageNamed:@"ImageName.png"];  

  // Request to save the image to camera roll
  UIImageWriteToSavedPhotosAlbum(img, self, 
              @selector(image:didFinishSavingWithError:contextInfo:), nil);

Here we are specifying that the selector to be called upon completion is within this object (self). A template for this selector could look as follows:

  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error 
             contextInfo:(void *)contextInfo
  {
    // Was there an error?
    if (error != NULL)
    {
      // Show error message...

    }
    else  // No errors
    {
      // Show message image successfully saved
    }
  }

Add code for displaying the appropriate message based on success or failure of the image save, and you’re good to go.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s