Programmatically save image to camera roll


Smartphone app development is on the roll. Recently I came across a situation to save image directly to camera roll of Photos app of  iPhone. I googled for the same and found a code snippets that save image to camera roll. I am sharing the same in this post

We can save image to camera roll of photos app by using the inbuilt method provided in the SDK. Method name is UIImageWriteToSavedPhotosAlbum and its complete syntax is

void UIImageWriteToSavedPhotosAlbum (
   UIImage  *image,
   id       completionTarget,
   SEL      completionSelector,
   void     *contextInfo
);
It takes three parameters
image: image we want to save in camera roll.
completetionTarget: object whose selector would gets called when image was written successfully.
completionSelector: selector to be gets called. The method should conforms to following signature
– (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo;
contextInfo: An optional pointer to any context-specific data that you want passed to the completion selector.
Now we are done with explanation lets create a demo project named saveToCameraRoll and set prefix as SCR. 
Open SCRViewController.h and create an IBOutlet to UIImageView named imageView and declare an IBAction named saveToCameraRoll
#import
@interface SCRViewController : UIViewController
{
    IBOutlet UIImageView *imageView;
}
-(IBAction)saveToCameraRoll:(id)sender;
@end
Open Main.storyboard and drag an UIImageView object to view and UIButton, change its tittle to SAVE. Add an image to Xcode project and set it as UIImageView image.Connect IBOutlet to UIImageView and IBAction to UIButton.
Open SCRViewController.m file an define our IBAction
-(IBAction)saveToCameraRoll:(id)sender
{
    UIImage *imageToBeSaved = imageView.image;
    UIImageWriteToSavedPhotosAlbum(imageToBeSaved, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
– (void)image:(UIImage *)image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    if (!error)
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@”Success!” message:@”The picture was saved successfully to your Camera Roll.” delegate:nil cancelButtonTitle:@”OK” otherButtonTitles: nil];
        [alert show];
    }
}
Here in above code we are saving image to camera roll of photos app by using the inbuilt method name UIImageWriteTOSavedPhotoAlbum. We want to get notified about the image saved to camera roll or not that’s why we pass selector and the define it. This is optional and you can pass nil value also. When image gets saved successfully we were notified by the selector and showed user an alert if its a successful operation. You can grab source code for the above code or demo from given below link.
Video: