ActionSheet to show Camera and Gallery to get the Image iOS Swift 3
First, you can create an image picker above viewDidLoad
var Picker = UIImagePickerController()
class ViewController: UIViewController,UIAlertViewDelegate,UIImagePickerControllerDelegate
let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.default)
{
UIAlertAction in
self.openCamera()
}
let galleryAction = UIAlertAction(title: "Gallery", style: UIAlertActionStyle.default)
{
UIAlertAction in
self.openGallery()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel)
{
UIAlertAction in
}
Picker.delegate = self
alert.addAction(cameraAction)
alert.addAction(galleryAction)
alert.addAction(cancelAction)
//You must add this line then only in iPad it will not crash
alert.popoverPresentationController?.sourceView = self.view
self.present(alert, animated: true, completion: nil)
default:
break
// MARK: - Photo Actions
func openCamera()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
{
self.Picker.sourceType = UIImagePickerControllerSourceType.camera;
self .present(self.Picker, animated: true, completion: nil)
self.Picker.allowsEditing = false
self.Picker.delegate = self
}
}
func openGallery()
{
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum){
self.Picker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum;
self.Picker.allowsEditing = false
self.Picker.delegate = self
self.present(self.Picker, animated: true, completion: nil)
}
}
Below are after picking the image you can set the image to image view from camera or Gallery
// MARK: - Image Picker Delegate methods
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
self.ImageView.image = (info[UIImagePickerControllerOriginalImage] as? UIImage)
self.dismiss(animated: true, completion: nil)
}
Delegate not getting called
ReplyDeleteIn your viewdidload add self.Picker.delegate = self
Deletethen it will works good