views:

42

answers:

2

Hello,

I'm trying to save a selected image to a directory. My code is as follows:

-(IBAction)attachPhotosButton
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 

    [self presentModalViewController:imagePicker animated:YES];

    // If image is selected, then save
        //[self saveImage];
    // else do nothing
}


-(void)saveImage 
{
    // This creates a string with the path to the app's Documents Directory.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    // Here we are calling the method we created before to provide us with a unique file name.
    NSString *imagePath = [NSString stringWithFormat:@"%@/iPhoneImage.png", documentsDirectory];

    // This creates PNG NSData for the UIImageView imageView's image.
    UIImageView *imageView;
    NSData *imageData = UIImagePNGRepresentation(imageView.image);

    // Uncomment the line below to view the image's file path in the Debugger Console. (Command+Shift+R)
    NSLog(@"Image Directory: %@", imagePath);

    // This actually creates the image at the file path specified, with the image's NSData.
    [[NSFileManager defaultManager] createFileAtPath:imagePath contents:imageData attributes:nil];
}

How do I detect that the user selected an image when the imagePicker view controller is presented ?

If they select an image I want to call the saveImage method.

Regards, Stephen

+1  A: 

in the

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

delegate method of UIImagePickerControllerDelegate.

Edit: reread your question and realized you want to save to your temp path or somewhere, not the phone's photo album.

Jesse Naugher
How can you get an image from the savedPhotosAlbum. Do you need to present the UIImagePickerController again?
vodkhang
read the documentation on UIImagePickerControllerDelegate @MishieMoo so kindly provided in another answer.
Jesse Naugher
+2  A: 

You need to access the UIImagePickerControllerDelegate methods. The link brings you to the one you want. Make sure that you set the picker delegate!

Inside the method you just need to check if the UIImagePickerControllerMediaType key of the info dictionary is set to a kUTTypeImage. Then call your function.

MishieMoo