Melissa Rojas Melissa Rojas - 4 months ago 46
Swift Question

Warning: Attempt to present <UIImagePickerController: > on <...> which is already presenting (null)

I am looking for some help here!

I have an ActionController in swift and I am trying to present a UIImagePickerController from one of the actions created, but when I run it, It is showing me this Warning: Attempt to present on <...> which is already presenting (null), and It is not presenting anything.

Here is my code:

let actionController = TweetbotActionController()



actionController.addAction(Action("Photo Library", style: .Default , handler: { action in
let picker = UIImagePickerController()
picker.sourceType = .PhotoLibrary
picker.allowsEditing = false
picker.delegate = self

self.presentViewController(picker, animated: true, completion: nil)


}))

actionController.addAction(Action("Take Photo", style: .Default, handler: {action in

NSLog("Take Photo Pressed")
}))

actionController.addSection(Section())
actionController.addAction(Action("Cancel", style: .Cancel, handler:nil))

presentViewController(actionController, animated: true, completion:nil)


Thanks a lot !!!

Answer

The error message is quite self explanatory. You just can't have two view controllers presented at the same time.

You should first close the AlertController and then open the new one. For achieving this you have several options, but I believe the easiest is to close the AlertController when you press "Photo Library" and set some kind of flag there. This can be a variable named shouldOpenPicker that will be always false unless you press the button.

Then you can use the completion closure of the presentViewController (the one that presented AlertController) to open the picker controller only if the flag variable is set to true. If it is, you present the picker controller and set the flag to false again.

UPDATE:

You should present the second view controller when dismissed the first one, something like this:

alert.addAction(UIAlertAction(title: "Photo library", style: .Default, handler: { action in
    alert.dismissViewControllerAnimated(true, completion: {
        let picker = UIImagePickerController()
        picker.sourceType = .PhotoLibrary
        picker.allowsEditing = false
        picker.delegate = self

        self.presentViewController(picker, animated: true, completion: nil)
    })
}))
Comments