Implementing UIImagePickerController to Open Camera in iOS App | iOS Programmer Guide | Xcode Programmer Guide
iOS
The UIImagePickerController can be used to take pictures using the camera. In order to work with UIImagePickerController you need to make sure that your controller uses the UINavigationControllerDelegate and UIImagePickerControllerDelegate as shown in the following implementation:
1 | @ interface ViewController : UIViewController<UINavigationControllerDelegate, UIImagePickerControllerDelegate> |
The takePicture method initiates the camera and allow the user to take pictures. If you are not testing it on a real hardware device then the simulator can display the photo library or the photo album. The implementation is shown below:
01 | -( void ) takePicture:(id) sender |
03 | UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; |
05 | if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) |
07 | [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera]; |
11 | [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; |
14 | [imagePicker setDelegate:self]; |
16 | [self presentModalViewController:imagePicker animated:YES]; |
The takePicture method creates an instance of the UIImagePickerController and checks if the device has the camera or not. If the camera is found then the SourceType is set as UIImageControllerSourceTypeCamera otherwise the SourceType is set as UIImagePickerSourceTypePhotoLibrary. The camera is presented inside the model view controller. If you run the application on the simulator you will see the Photo Library as shown in the screenshot below: When the picture is taken the didFinishPickingMediaWithInfo method of the UIImagePickerControllerDelegate is invoked. The didFinishPickingMediaWithInfo parameter info has the information about the new image. The implementation below shows how to set the new image to the UIImageView control on the view.
1 | -( void ) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info |
3 | UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; |
5 | [self.imageView setImage:image]; |
6 | [self dismissModalViewControllerAnimated:YES]; |
The last line [self dismissModalViewControllerAnimated:YES]; is extremely important. If you do not dismiss the model view controller then you will be stuck at the camera screen. The picture is then displayed on the view using the UIImageView control.