Search code examples
swiftuinavigationcontrolleruitabbarcontrolleruiimagepickercontrollerdismiss

UIImagePickerController dismiss not properly


There are 5 items in UITabbarController: VC0, VC1, VC3(default selected), VC4, VC5.

UITabbarController > NavigationController > VC1 > VC1-A

UIImagePickerController is presented in VC1-A:

let imagePickerController = UIImagePickerController()
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
imagePickerController.allowsEditing = false
self.present(imagePickerController, animated: false)

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)

    if let image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage{
       topImage.image = image
    }

    picker.dismiss(animated: true, completion: nil)

}

When image is selected and the picker is dismissed, the view will go to the default selected item VC3, but not VC1-A.

I found this in a resent test on App, but I remember it worked properly before. I now cannot recall what I did that may make it not proper, Xcode update, Swift version update? I do know that I make no change on this part.

The following tries not work either:

self.navigationController?.present(imagePickerController, animated: false)
self.navigationController?.dismiss(animated: true, completion: nil)
self.navigationController?.popViewController(animated: true)
picker.popViewController(animated: true)

By now I make it works like this:

picker.dismiss(animated: true, completion: {
        self.tabBarController?.selectedIndex = 1
    })

But it's not a good idea to solve the problem, hope someone can give a proper solution. Thanks.


Solution

  • You should get tabBarController of VC1-A's navigation controller and change selected index

    picker.dismiss(animated: true) {//dismiss image picker
        if let navigationController = self.navigationController {
            navigationController.popToRootViewController(animated: true)//go to VC1
            navigationController.tabBarController?.selectedIndex = 2//go to VC3
        }
    }