M O
M O

Reputation: 1

How can I properly pass data to previous viewController(which has navigation)?

I want to pass text data to previous viewController(vcA) from the current viewController(vcB). Both viewControllers has navigationBar and it transitions from vcA to vcB by code below(it transitions modaly).

// in vcA file
let nextView = self.storyboard?.instantiateViewController(identifier: "nextView")
let nav = UINavigationController(rootViewController: nextView!)
present(nav,animated: true,completion: nil)

I want to pass data to vcA when dismiss method is called in vcB anc save text data at this time in vcB. What is the proper way to pass data to previous viewController?

Upvotes: 0

Views: 70

Answers (2)

SachinVsSachin
SachinVsSachin

Reputation: 6427

Like delegate pattern, we can also use closure's. I prefer in this situation Closure's eg.

class ParentViewController: UIViewController {
    
    func navigateToChildViewController() {
        let childController = ChildViewController()
        childController.selectionCompletion = { message in
            print(message) //print Hello world
        }
        self.present(childController, animated: true)
    }
}

class ChildViewController: UIViewController {
    var selectionCompletion: ((String) -> Void)?

    //method can be any, here I take example of this method
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //This callback, will pass this string value back to it's parent controller
        selectionCompletion?("Hello World")
    }
}

Upvotes: 1

Mehbube Arman
Mehbube Arman

Reputation: 490

You can try passing a callback viewController B like bellow

class AController: UIViewController, ControllerDataDelegate { 
    func presentNewController() { 
        let bController = BController.get(listener: self)
        self.present(bController, animated: true)
    }

    func onDataReady(_ data: String) { 
         // do what you want with this string
    } 
}

protocol ControllerDataDelegate { 
     func onDataReady(_ data: String)
}

class BController: UIViewController { 
    class func get(listener: ControllerDataDelegate) { 
       let controller = BController.init()
       controller.listener = listener
       return controller
    }

    private var listener: ControllerDataDelegate!

    // any time you want to notify previous view controller
    func notify(with data: String) { 
        self.listener(data)
    }

    // call this function when you want to close and return some data
    func requestClose(animated: Bool = true, with data: String) { 
         self.dismiss(animated: animated, completion: { 
             self.notify(with: data)
         })
    }
}

Upvotes: 0

Related Questions