-1

My question is duplicate but I need not a suitable answer. Also, I have raised the same before how to callback the array of data to another viewController in iOS Swift

I have a parent viewController called CreateCardViewController and a child controller called webViewController.

In parent viewController, I have used carbonKit for showing the tab bar menu. When the tab bar menu first index is webViewController (that's a child controller).

My question is: How to send data to the parent controller from the child controller?

For example: From a child, viewController will get a list of tab bar menu items. After getting tab bar menu items, I need to send menu items to parent viewController to show tab bar.

Here is the clear picture, which I am trying to do:

enter image description here

Swift Dev Journal
  • 19,282
  • 4
  • 56
  • 66
PvUIDev
  • 95
  • 1
  • 9
  • 38

2 Answers2

1

you can use delegate like what @Aqua said. or use observation for this.

class ParentViewController: UIViewController {
 override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(self.updateParentViewController(_:)), name: Notification.Name(rawValue: "updateParentViewController"), object: nil) 
 }
@IBaction func updateParentViewController(_ notification: NSNotification){
if let receivedData = notification.userInfo?["data"] as? Any {
    //use received data 
    // update your parentViewController. 
}
}
}

//.............

class ChildViewController: UIViewController {
     override func viewDidLoad() {
        super.viewDidLoad()
}
func sendDataToParentViewController() {
        let dataDict:[String: Any] = ["data"://what you want to send.]
        NotificationCenter.default.post(name: . updateParentViewController, object: nil, userInfo: dataDict)
    }
}

this works for me.

0

On your custom ChildViewController add propertyparentViewController and set it when you create that child view controller. Then, implement specific method on parent viewcontroller, that receives data from child view controller.

protocol ParentViewControllerProtocol {
    func receiveChildData(_ child: UIViewController, data: Any)
}

class ChildViewController: UIViewController {
    var parentViewController: ParentViewControllerProtocol!

    func timeToSendDataToParentViewController() {
         parentViewController.receiveChildData(self, data: self.data)
    }
}

class ParentViewController: UIViewController, ParentViewControllerProtocol {
     func receiveChildData(_ child: UIViewController, data: Any) {/*handle data*/}

     func addChildViewController() {
        let child = ChildViewController();
        child.parentViewController = self
        // do the rest of adding child to parent
     }
}
Aqua
  • 716
  • 8
  • 10
  • it shows error Property 'parentViewController' with type 'ParentViewControllerProtocol?' cannot override a property with type 'UIViewController?' – PvUIDev Mar 02 '20 at 06:23