These are notes from Lecture 16 of Paul Hegarty’s iPhone App Dev course.

UIImagePickerController is just a modal view controller to get media from your camera of photo library.
Modal means you put it up with presentViewController:animated:completion

Usage
1. Create it with alloc/init and set delegate.
2. Configure it (source, kind of media, user editability).
3. Present it.
4. Respond to delegate method when user done picking media.

In this example we are going to allow ourselves to take a picture and put it in our KitchenSink view.

Create a button to trigger taking a picture with an outlet called addImage.

ViewController.m

- (IBAction)addImage:(UIBarButtonItem *)sender {

}

Then import the MobileCoreService library (click here for reminder on how to do this).

Note: UIImagePickerController is in fact a UINavigationController. And it has a property called delegate as well. It’s overloaded.

So when we implement the UIPickerControllerDelegate we also have to say we are a UINavigationControllerDelegate.

@interface KitchenSinkViewController()

Now do all the work to figure out what kind of device you are on, and what kind of pictures you can take:

- (IBAction)addImage:(UIBarButtonItem *)sender {
    
    // figure out our media types
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        if ([mediaTypes containsObject:(NSString *)kUTTypeImage]) {
            // create our image picker
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeImage];
            picker.allowsEditing = YES;
            [self presentModalViewController:picker animated:YES];
        }
    }
}

Now need to implement the image picker delegate methods:

#define MAX_IMAGE_WIDTH 200

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    if (!image) image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (image) {
        // keep the image view reasonable - reduce size
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        CGRect frame = imageView.frame;
        while (frame.size.width > MAX_IMAGE_WIDTH) {
            frame.size.width /= 2;
            frame.size.height /= 2;
        }
        imageView.frame = frame;
        [self setRandomLocationForView:imageView];
        [self.kitchenSink addSubview:imageView];
    }
    [self dismissImagePicker];
}

Can’t demo this because I build project against iPad and for some reason doesn’t work when I deploy to my iPhone.