Search code examples
iosobjective-ciphoneswiftuiimagepickercontroller

Dismissing of UIImagePickerController dismisses presenting view controller also


I am working on a project that uses tabbar system. One of the item of tabbar is JobPostingViewController. I Embed it in UINavigationController. There is a UIButton called add new job in this view controller .I implemented pushviewcontroller to go CreateJobPostViewController. There I need to add UIImagePickerController to choose the image. When i tap done button or choose an image from library it dismisses to JobPostingViewController. But it should go to the CreateJobPostViewController. Any one please help me. Thanks in advance.

You can see the issue here:
enter image description here

Code in JobPostingViewController

 @IBAction func openCreateJob(sender: AnyObject) {
    let vc = self.storyboard?.instantiateViewControllerWithIdentifier("CreateJobPostViewController") as! CreateJobPostViewController
    self.navigationController?.pushViewController(vc, animated: true)
}

Code in CreateJobPostViewController

   @IBAction func addImages(sender: AnyObject) {
    imagePicker.allowsEditing = false
    imagePicker.sourceType = .PhotoLibrary
    presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    picker.dismissViewControllerAnimated(true, completion: nil)
}

Solution

  • Adding Picker as subview

    try to add the imagepicker as a subview to your CreateJobPostViewController insted of presenting it and then remove it from parent in the delegtes

    @IBAction func openCreateJob(sender: AnyObject) {
    
    var picker: UIImagePickerController = UIImagePickerController()
    picker.delegate = self
    picker.allowsEditing = false
    picker.sourceType = .PhotoLibrary
    self.addChildViewController(picker)
    picker.didMoveToParentViewController(self)
    self.view!.addSubview(picker.view!)
    }
    

    and then

     func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    
        picker.view!.removeFromSuperview()
        picker.removeFromParentViewController()
        }
    

    For presenting

    showing picker over currentcontext with options like edit cancel choose,

    use picker.modalPresentationStyle = .overCurrentContext //before presenting it

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