Step 1: Create the controller, set the delegate, and conform to the protocol
//Swift
class ImageUploadViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let imagePickerController = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePickerController.delegate = self
}
}
//Objective-C
@interface ImageUploadViewController : UIViewController <UIImagePickerControllerDelegate,UINavigationControllerDelegate> {
UIImagePickerController *imagePickerController;
}
@end
@implementation ImageUploadViewController
- (void)viewDidLoad {
[super viewDidLoad];
imagePickerController.delegate = self;
}
@end
note: We actually will not implement anything defined in UINavigationControllerDelegate
, but UIImagePickerController
inherits from UINavigationController
and changes the behavior of UINavigationController
. Therefore, we still need to say our view controller conforms to UINavigationControllerDelegate
.
Step 2: Whenever you need to show UIImagePickerController
:
//Swift
self.imagePickerController.sourceType = .Camera // options: .Camera , .PhotoLibrary , .SavedPhotosAlbum
self.presentViewController(self.imagePickerController, animated: true, completion: nil)
//Objective-C
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; // options: UIImagePickerControllerSourceTypeCamera, UIImagePickerControllerSourceTypePhotoLibrary, UIImagePickerControllerSourceTypeSavedPhotosAlbum
[self presentViewController:imagePickerController animated:YES completion:nil];
Step 3: Implement the delegate methods:
//Swift
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// Your have pickedImage now, do your logic here
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
//Objective-C
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *pickedImage = info[UIImagePickerControllerOriginalImage];
if (pickedImage) {
//You have pickedImage now, do your logic here
}
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:nil];
}