It’s pretty simple to use the camera (front, rear and camera albums) in an iphone application.
To get started just create an instance of UIImagePickerController with:
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
After you need to decide the source of the image you want to capture. There are these possible values:
- UIImagePickerControllerSourceTypeCamera – this will get the image from the camera.
- UIImagePickerControllerSourceTypePhotoLibrary – this will open the album list of the photos app.
- UIImagePickerControllerSourceTypeSavedPhotosAlbum – this will open the camera roll
you can specify which one you want with:
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
You can also specify if you want the user to be able to edit the image (with cropping) with the property:
picker.allowsImageEditing = YES;
After you need to set a delegate to the controller. This delegate must implement the UIImagePickerControllerDelegate protocol at least this method:
- – (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
this method will receive a dictionary containing some info about the chosen picture. The original image selected (without editing) will be under the key “UIImagePickerControllerOriginalImage”, the edited image (if you allowed the user to edit) will be under the key “UIImagePickerControllerEditedImage”. These properties are both instances of UIImage. You can even get the selected frame if the user edited the picture, with the property “UIImagePickerControllerCropRect”. This will be an instance of CGRect.
Finally to present the view controller, just invoke in your view controller:
[self presentModalViewController:picker animated:YES];
One last thing that is worth mentioning is that you can verify if your device has a camera before allowing him to use it.
To test if the user has a camera device just use this method (that returns a boolean):
You can also query the user about the front camera with the parameter: UIImagePickerControllerCameraDeviceFront.
Knowing that a user does not even has a camera, may help you prevent a broken experience to the user.
Well, that’s all folks, at least for now.
Hope you enjoyed this tutorial.