The UIImagePickerController can help us do this with ease.
In this example we’ll instantiate an image picker and tell it what kind of image we want returned. We have a choice of using an edited version, use the original, or start using a camera. Next we present the picker from which the user can select the image:
[emember_protected]
1 2 3 4 5 6 7 8 |
// let's grab a picture from the media library UIImagePickerController *myPicker = [[UIImagePickerController alloc]init]; myPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; myPicker.allowsEditing = YES; myPicker.delegate = self; // now we present the picker [self presentViewController:myPicker animated:YES completion:nil]; |
For this to work you need to conform to both the UIImagePickerControllerDelegate protocol, as well as the UINavigationControllerDelegate. The latter does not need to conform to any methods – but without it we’d get a warning.
The two methods we need to conform to the first protocol are dealing with selection and cancellation. In this example I’m displaying the returned image in a UIImageView:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// an image is selected - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [self dismissViewControllerAnimated:YES completion:nil]; UIImage *chosenImage = [info objectForKey:UIImagePickerControllerEditedImage]; self.myPicture.image = chosenImage; } // user hits cancel - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [self dismissViewControllerAnimated:YES completion:nil]; } |
[/emember_protected]