Here's how to use the new image picker API in a nutshell.
First, you need a class declared like this since it's setting itself as the image picker delegate:
@interface MyClass : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate> {
UIImagePickerController* imagePicker;
}
@property(nonatomic,retain) UIImagePickerController* imagePicker;
- (IBAction) takePicture:(id)sender;
@end
The method that brings up the image picker would go something like this. It's declared here as an IBAction
so you can directly wire it to a control (like a button) in Interface Builder. It also checks so that if you're on an iPhone it brings up the camera interface but on an iPod Touch it brings up the gallery picker:
#import <MobileCoreServices/UTCoreTypes.h>
...
@synthesize imagePicker = _imagePicker;
...
- (void) takePicture:(id)sender
{
if (!_imagePicker) {
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.delegate = self;
}
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
NSArray* mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
self.imagePicker.mediaTypes = mediaTypes;
} else {
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.imagePicker.allowsImageEditing = YES;
}
[self presentModalViewController:self.imagePicker animated:YES];
}
Then you need these two methods:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
// MediaType can be kUTTypeImage or kUTTypeMovie. If it's a movie then you
// can get the URL to the actual file itself. This example only looks for images.
//
NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];
// NSString* videoUrl = [info objectForKey:UIImagePickerControllerMediaURL];
// Try getting the edited image first. If it doesn't exist then you get the
// original image.
//
if (CFStringCompare((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
UIImage* picture = [info objectForKey:UIImagePickerControllerEditedImage];
if (!picture)
picture = [info objectForKey:UIImagePickerControllerOriginalImage];
// **You can now do something with the picture.
}
self.imagePicker = nil;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
self.imagePicker = nil;
}