O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.4. Storing Photos in the Photo Library

Problem

You want to be able to store a photo in the user’s photo library.

Solution

Use the UIImageWriteToSavedPhotosAlbum procedure:

- (void) imageWasSavedSuccessfully:(UIImage *)paramImage
          didFinishSavingWithError:(NSError *)paramError
                       contextInfo:(void *)paramContextInfo{

    if (paramError == nil){
        NSLog(@"Image was saved successfully.");
    } else {
        NSLog(@"An error happened while saving the image.");
        NSLog(@"Error = %@", paramError);
    }

}

- (void)  imagePickerController:(UIImagePickerController *)picker
  didFinishPickingMediaWithInfo:(NSDictionary *)info{

    NSLog(@"Picker returned successfully.");

    NSLog(@"%@", info);

    NSString     *mediaType = info[UIImagePickerControllerMediaType];

    if ([mediaType isEqualToString:(__bridge NSString *)kUTTypeImage]){

        UIImage *theImage = nil;

        if ([picker allowsEditing]){
            theImage = info[UIImagePickerControllerEditedImage];
        } else {
            theImage = info[UIImagePickerControllerOriginalImage];
        }

        SEL selectorToCall =
        @selector(imageWasSavedSuccessfully:didFinishSavingWithError:\
                  contextInfo:);

        UIImageWriteToSavedPhotosAlbum(theImage,
                                       self,
                                       selectorToCall,
                                       NULL);

    }

    [picker dismissViewControllerAnimated:YES completion:nil];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{

    NSLog(@"Picker was cancelled");
    [picker dismissViewControllerAnimated:YES completion:nil];

}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    static BOOL beenHereBefore = NO;

    if (beenHereBefore){
        /* Only display the picker ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required