I want to offer the option to use either the photo library or the camera, but my alert to select either photos or use a camera doesn't show up when I add the present actionSheet. The compiled application goes straight to photo album without giving me the option to select camera or photo library.
This is the log from my Xcode 11:
2020-06-15 23:05:22.931477-0400 MeMe[6298:3505455] Attempt to present
on which is waiting for a delayed presention of
to complete 2020-06-15
23:05:22.931653-0400 MeMe[6298:3505455] Attempt to present
on
which is waiting for a delayed presention of to complete error in connection_block_invoke_2:
Connection interrupted
This is my code:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
// OUTLETS *******************************************
// Image
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
// ACTIONS *******************************************
// Button
#IBAction func pickImage(_ sender: Any) {
let imagePickerController = UIImagePickerController()
// set imagePickerController as delegate
imagePickerController.delegate = self
// provide actionSheet to display the camera and photo options
let actionSheet = UIAlertController(title: "Source", message: "Take a picture or select a photo", preferredStyle: .actionSheet)
// add camera action to imagePickerController
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler:{(action:UIAlertAction) in
// check if the camera is available
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController.sourceType = .camera
}
else {
print("Camera not available")
}
}))
self.present(imagePickerController, animated: true, completion: nil)
// add photos action to imagePickerController
actionSheet.addAction(UIAlertAction(title: "Photos", style: .default, handler:{(action:UIAlertAction) in imagePickerController.sourceType = .photoLibrary}))
self.present(imagePickerController, animated: true, completion: nil)
// cancel
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
// assign image to imageView
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
imageView.image = image
picker.dismiss(animated: true, completion: nil)
}
// dismiss the image selector
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
You're trying to present the actionSheet after presenting imagePickerController which is not possible. You need to present the imagePickerController in the UIAlertAction's handler block. Here's the code:
#IBAction func pickImage(_ sender: Any) {
let imagePickerController = UIImagePickerController()
// set imagePickerController as delegate
imagePickerController.delegate = self
// provide actionSheet to display the camera and photo options
let actionSheet = UIAlertController(title: "Source", message: "Take a picture or select a photo", preferredStyle: .actionSheet)
// add camera action to imagePickerController
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler:{(action:UIAlertAction) in
// check if the camera is available
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController.sourceType = .camera
}
else {
print("Camera not available")
}
self.present(imagePickerController, animated: true, completion: nil)
}))
// add photos action to imagePickerController
actionSheet.addAction(UIAlertAction(title: "Photos", style: .default, handler:{(action:UIAlertAction) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}))
// cancel
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
#IBAction func pickImage(_ sender: Any) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let actionSheet = UIAlertController(title: "Source", message: "Take a picture or select a photo", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler:{(action:UIAlertAction) in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
} else {
print("Camera not available")
}
}))
actionSheet.addAction(UIAlertAction(title: "Photos", style: .default, handler:{(action:UIAlertAction) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}))
// cancel
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
Related
I've tried to save UIImage on UIViewcontroller named secondViewController, But didn't work.
Code snippet for saving image is attached.
#IBAction func takePhoto(_ sender: Any) {
cameraSession.stopRunning()
UIImageWriteToSavedPhotosAlbum(self.cameraImageView.image!, nil, nil, nil)
}
On SecondViewController, UIImage has been saved to cameraImageView.image,
But when check camera roll, nothing saved.
Does anyone know why?
Add Permission in your info.plist
"Privacy - Photo Library Additions Usage Description"
After permission granted try to save image.
#IBAction func takePhoto(_ sender: Any) {
cameraSession.stopRunning()
UIImageWriteToSavedPhotosAlbum(self.cameraImageView.image!, nil, nil, nil)
}
hey I added full code to capture image using UIImagePickerController and also added code to import a photo from photo gallery, hope it will helpful for you
import UIImagePickerControllerDelegateand create a variable to assign UIImagePickerController var imagePicker = UIImagePickerController()
and set imagePicker.delegate = self.
Create a action sheet to display options for 'Camera' and 'Photo library'.
On your button click action:
#IBAction func buttonOnClick(_ sender: UIButton)
{
self.btnEdit.setTitleColor(UIColor.white, for: .normal)
self.btnEdit.isUserInteractionEnabled = true
let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
self.openCamera()
}))
alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
self.openGallary()
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
/*If you want work actionsheet on ipad
then you have to use popoverPresentationController to present the actionsheet,
otherwise app will crash on iPad */
switch UIDevice.current.userInterfaceIdiom {
case .pad:
alert.popoverPresentationController?.sourceView = sender
alert.popoverPresentationController?.sourceRect = sender.bounds
alert.popoverPresentationController?.permittedArrowDirections = .up
default:
break
}
self.present(alert, animated: true, completion: nil)
}
func openCamera() {
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
{
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
else
{
let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func openGallary() {
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
I'm trying to give the user two options uploading an image, the first the the photo library, and the second is the camera. I have an Actionsheet where the user can choose which way he wants to upload an image, but when clicking on the camera option, the camera app won't open. I did add the Privacy needed in the plist file.
This is my actionsheet code:
extension MoreReportsVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func handleAddPhoto() {
showSimpleActionSheet(controller: self)
}
func showSimpleActionSheet(controller: UIViewController) {
let alert = UIAlertController(title: "Add a photo", message: "Please Select an option", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "From photo library", style: .default, handler: { (_) in
self.imagePicker.getImage(fromSourceType: .photoLibrary)
}))
alert.addAction(UIAlertAction(title: "Open camera app", style: .default, handler: { (_) in
self.imagePicker.getImage(fromSourceType: .camera)
}))
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { (_) in
print("User click Dismiss button")
}))
self.present(alert, animated: true, completion: {
print("completion block")
})
}
}
This is my ImagePicker code:
class ImagePickerManager: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var placeholderImage: UIImageView?
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//TODO:
}
func getImage(fromSourceType sourceType: UIImagePickerController.SourceType){
if UIImagePickerController.isSourceTypeAvailable(sourceType){
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.sourceType = sourceType
self.present(imagePickerController, animated: true, completion: nil)
}
}
}
The imagePicker in the actionsheet, is just a ImagePickerManager variable.
The app won't crash or anything, and it is getting to the getImage method, but just don't open the camera.
EDIT: I think the problem is in the delegate = self. self needs to be the VC I try to view the imagepicker from if im not wrong. and currently it is ImagePickerManager but I can't find a way to set it as my VC.
The problem is that your ImagePickerManager isn't actually a reference to any view controller currently in the interface. Thus, self.present does nothing because self is not the current view controller.
If you want to put image picker management into an encapsulated class that is not the current view controller, the encapsulation should not itself be a view controller; it should just be an ordinary object. You then won't be able to say self.present, so you will need to provide this object with a reference to the current view controller, which is in this case your MoreReportsVC.
Add getImage method in UIViewController extension like this.
extenstion UIViewController {
func getImage(fromSourceType sourceType: UIImagePickerController.SourceType){
if UIImagePickerController.isSourceTypeAvailable(sourceType){
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.sourceType = sourceType
self.present(imagePickerController, animated: true, completion: nil)
} else {
print("Source type isn't available")
}
}
}
And call this method from showSimpleActionSheet method from self
func showSimpleActionSheet(controller: UIViewController) {
let alert = UIAlertController(title: "Add a photo", message: "Please Select an option", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "From photo library", style: .default, handler: { (_) in
self.getImage(fromSourceType: .photoLibrary)
}))
alert.addAction(UIAlertAction(title: "Open camera app", style: .default, handler: { (_) in
self.getImage(fromSourceType: .camera)
}))
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { (_) in
print("User click Dismiss button")
}))
self.present(alert, animated: true, completion: {
print("completion block")
})
}
}
I am new to programming in general and was having trouble with memory leak problems with the following code specifically involving the "imagePickerController." The leaks only occur after the UIimagePickerController is dismissed after selecting an image. Thank you for any help fixing this.
let imagePicked = UIImagePickerController()
#IBAction func addPhoto(_ sender: UIBarButtonItem) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.allowsEditing = false
imagePicked.delegate = self
let alertController = UIAlertController(title: "Add New Image", message: "Choose From", preferredStyle: .actionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: .default) { (action) in
pickerController.sourceType = .camera
self.present(pickerController, animated: true, completion: nil)
}
let photosLibraryAction = UIAlertAction(title: "Photos Library", style: .default) { (action) in
pickerController.sourceType = .photoLibrary
self.present(pickerController, animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
alertController.addAction(cameraAction)
alertController.addAction(photosLibraryAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
#objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
var newImageView = UIImageView()
newImageView = UIImageView(image: image)
newImageView.contentMode = .scaleAspectFit
newImageView.center = textView.center
textView.addSubview(newImageView)
}
dismiss(animated: true, completion: nil)
}
EDIT ONE:
Thank you I have removed #objc in front of didFinishPickingMediaWithInfo as well as the extra UIImagePickerController object, but I am still having the same problem. I have also tried picker.dismiss(animated: true, completion: nil) but that is still not fixing the problem.
And yes I am pretty sure it is a memory leak error as I've ran the tester and after putting pictures into the app from the photos library or the camera I am getting this:
picture 1
picture 2
Also after adding several pictures the app will crash with "Terminated due to memory problem"
Opening the UIAlertController on button click, the action is going to open but main issue is the UIAlertAction methods are not performed on its click. Here is Code block :
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// getData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//menuBtn is the button
#IBAction func menuBtn(sender: UIButton) {
let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let orders = UIAlertAction(title: "Orders", style: .Default, handler: { (alert: UIAlertAction!) -> Void in
let alertViewController = self.storyboard?.instantiateViewControllerWithIdentifier("OrdersViewController") as! OrdersViewController
self.presentViewController(alertViewController, animated: true, completion: nil)
})
let about = UIAlertAction(title: "About", style: .Default, handler: {(alert: UIAlertAction!) -> Void in
let aboutObject = self.storyboard?.instantiateViewControllerWithIdentifier("AboutViewController") as! AboutViewController
self.presentViewController(aboutObject, animated: true, completion: nil)
})
let contactUs = UIAlertAction(title: "Contact Us", style: .Default, handler: {(alert: UIAlertAction!) -> Void in
let alertViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContactViewController") as! ContactViewController
self.presentViewController(alertViewController, animated: true, completion: nil)
})
let login = UIAlertAction(title: "LogIn", style: .Default, handler: {(alert: UIAlertAction!) -> Void in
let alertViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
self.presentViewController(alertViewController, animated: true, completion: nil)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
optionMenu.addAction(orders)
optionMenu.addAction(about)
optionMenu.addAction(contactUs)
optionMenu.addAction(login)
optionMenu.addAction(cancelAction)
self.presentViewController(optionMenu, animated: true, completion: nil)
}
This is code is working fine, I have checked it's opening new viewController as well.
Cross check points:
Controller class and stroybaord are connected
Storyboard ID has been assigned
IBAction must be connected to IBOutlet
On the Button click Action you have to write code.. Try This code.
let alert = UIAlertController(title: "Saved", message: "Selected Frame is Saved", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Ok", style:.Default , handler: { (UIAlertAction) in
}))
//Add action like this
self.presentViewController(alert, animated: true, completion: nil)
Still need any help feel free to ask.
First of all check if the button action is touch up inside. Make the button action as touch up inside. Below code works for me. Hope this works for you as well. Change the action title according to your need.
#IBAction func menuBtn(sender: AnyObject) {
let actionSheet = UIAlertController()
let criticalAction = UIAlertAction(title : "CRITICAL" , style : UIAlertActionStyle.Default){
(action) in
//This section will be executed when the buttons are pressed
//Do your work here.
debugPrint("CRITICAL")
}
let highAction = UIAlertAction(title : "HIGH" , style : UIAlertActionStyle.Default){
(action) in
//This section will be executed when the buttons are pressed
//Do your work here.
debugPrint("HIGH")
}
actionSheet.addAction(criticalAction)
actionSheet.addAction(highAction)
self.presentViewController(actionSheet, animated: true, completion: nil)
}
How do I transfer a image to another view controller? For example this code takes a picture by using the camera functionality, the user confirms the image and displays it in the image view or can be selected from the gallery, how can I segue this to another custom class once the image has been chosen?
Here is the code in the ViewController.swift
#IBAction func btnImagePicker1Clicked(sender: AnyObject)
{
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 gallaryAction = UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openGallary()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
{
UIAlertAction in
}
// Add the actions
SKIP2.hidden = true
BUTTON2.hidden = false
picker?.delegate = self
alert.addAction(cameraAction)
alert.addAction(gallaryAction)
alert.addAction(cancelAction)
// Present the controller
if UIDevice.currentDevice().userInterfaceIdiom == .Phone
{
self.presentViewController(alert, animated: true, completion: nil)
}
else
{
popover=UIPopoverController(contentViewController: alert)
popover!.presentPopoverFromRect(btnClickMe.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
}
func openCamera1()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
{
picker!.sourceType = UIImagePickerControllerSourceType.Camera
self .presentViewController(picker!, animated: true, completion: nil)
}
else
{
openGallary1()
}
}
func openGallary1()
{
picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
if UIDevice.currentDevice().userInterfaceIdiom == .Phone
{
self.presentViewController(picker!, animated: true, completion: nil)
}
else
{
popover=UIPopoverController(contentViewController: picker!)
popover!.presentPopoverFromRect(btnClickMe.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
}
func imagePickerController1(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
picker .dismissViewControllerAnimated(true, completion: nil)
imageView.image=info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel1(picker: UIImagePickerController)
{
print("picker cancel.")
}
}