2

I have a tabBarController and in one of the tabs is a view named view2. In view2 have some code that runs in viewWillAppear. I also have an UIImagePickerController in view2.

fileprivate var imagePicker = UIImagePickerController()

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        runSomeCode()
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
           imageView.image = image
           imagePicker.dismiss(animated: true, completion: nil)
        }
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    imagePicker.dismiss(animated: true, completion: nil)
}

I realize that every time the imagePicker is presented then dismissed then inside viewWillAppear runSomeCode() runs. I don't want it to keep getting called.

I initially was using this code below but I realized that the code in viewWillAppear only runs if the view2 is being pushed on. If I switch tabs and come back it won't run.

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

       if (isMovingToParentViewController) || (isBeingPresented){

           runSomeCode()
       }else{
           //runs when switching tabs but also runs after the imagePicker is dismissed
       }
}

How can I check if the imagePicker is being presented or dismissed so that my code in viewWillAppear won't run?

Lance Samaria
  • 17,576
  • 18
  • 108
  • 256

1 Answers1

2

Even though the accepted answer with the so link works I found something easier. With the accepted answer you have to check wether the view is being pushed on AND wether it's being shown by a tab switch using a bool value and the TabBarDelegates. It works but it's a lot of work. My main concern was the code not running while the imagePicker was being presented or dismissed.

With this imagePicker test in viewWillAppear runSomeCode() only runs if the view is being pushed on and if there is a tab switch back to this view from another tab but it won't run if the imagePicker is being presented or dismissed:

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

       if imagePicker.isBeingDismissed == false{

           runSomeCode()
       }
}

And here is how you would get the same effect in viewWillDisappear. runSomeCode() only runs if the view is being popped off and if there is a tab switch from this view to another tab but it won't run if the imagePicker is being presented or dismissed::

override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

       if imagePicker.isBeingPresented == false{

           runSomeCode()
       }
}
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256