11.6. Retrieving Photos and Videos From the Photo Library

Problem

You want users to be able to pick a photo or a video from their photo library and use it in your application.

Solution

Use the UIImagePickerControllerSourceTypePhotoLibrary value for the source type of your UIImagePickerController and the kUTTypeImage or kUTTypeMovie value, or both, for the media type, like so:

- (BOOL) isPhotoLibraryAvailable{ return [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary]; } - (BOOL) canUserPickVideosFromPhotoLibrary{ return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary]; } - (BOOL) canUserPickPhotosFromPhotoLibrary{ return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary]; } - (void)viewDidLoad{ [super viewDidLoad]; if ([self isPhotoLibraryAvailable]){ UIImagePickerController *controller = [[UIImagePickerController alloc] init]; controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; NSMutableArray *mediaTypes = [[NSMutableArray alloc] init]; if ([self canUserPickPhotosFromPhotoLibrary]){ [mediaTypes addObject:(__bridge NSString *)kUTTypeImage]; } if ([self canUserPickVideosFromPhotoLibrary]){ [mediaTypes addObject:(__bridge NSString *)kUTTypeMovie]; } controller.mediaTypes = mediaTypes; controller.delegate = self; [self.navigationController presentModalViewController:controller animated:YES]; ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.