Search code examples
iosswiftuitabbarcontrollersegue

How to perform a segue "behind the scenes" when not on the active view controller?


Sorry if the title is confusing. I have a create post workflow that is on a tab in my tabBar. At the end, there is a "create" button to publish the post. Here is the code attached to pressing that button:

@objc func postButtonPressed() {
    let tokens = self.tagsView.tokens()
    let tokensArr = tokens!.map({
        (token: KSToken) -> String in
        return token.title
    })
    if MyVariables.isScreenshot == true {
        PostService.createImagePost(image: self.screenshotOut!, timeStamp: self.postDate!, tags: tokensArr, notes: addNotesTextView.text ?? "")
    } else {
        PostService.createVideoPost(video: self.videoURL!, timeStamp: self.postDate!, thumbnailImage: self.thumbnailImage!, tags: tokensArr, notes: addNotesTextView.text ?? "")
    }
    self.tabBarController?.selectedIndex = 0
    self.tabBarController?.tabBar.isHidden = false

    //performSegue(withIdentifier: "ShowHomeViewController", sender: nil)
}

This works in that the tabBarController switches back to my other Tab. But what I want is for it also to segue back to the cameraView Controller - the first step of the create post workflow so that when the user tabs back to this workflow, they are starting at the beginning and don't come back to the createPost ViewController (the last step) which is what's happening now.

How do I perform this segue "behind the scenes" so that this can happen?


Solution

  • I achieved this by performing an "unwind" segue with in the createPost button...

    @objc func postButtonPressed() {
        //post code//
        ...
    
            performSegue(withIdentifier: "unwindToCamera", sender: nil)
        }
    

    I added that unwind segue in the interface builder. Then in the CameraViewController I have:

    @IBAction func unwindToCamera(sender: UIStoryboardSegue) {
            self.tabBarController?.selectedIndex = 0
            self.tabBarController?.tabBar.isHidden = false
        }
    

    which switches the selectedIndex back to the home screen. However when you tab back over to the camera tab, we are back on the camera view controller because of the unwind segue done prior. This is the desired behavior. The one drawback is that I cannot do an unwind to camera segue without changing the selected tabBar index but my app currently has no reason for me to do that.