3

My scenario, I am trying to pass the value from ViewController B to ViewController A during dismiss the view controller. Here I used below code but I can’t able to get the value in ViewController A.

ViewController B

// protocol used for sending data back
protocol isAbleToReceiveData {
    func pass(data: String)  //data: string is an example parameter
}

// Making this a weak variable so that it won't create a strong reference cycle
var delegate: isAbleToReceiveData?

override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        self.delegate?.pass(data: "someData") //call the func in the previous vc
}

@IBAction func Click_action(_ sender: Any) {
        self.dismiss(animated: false, completion: nil)
        self.delegate?.pass(data: "someData") 
 }

ViewController A

class MyViewController: UIViewController, isAbleToReceiveData {

func pass(data: String) {
        print("USER: \(data)")
    }
}

// MARK: FromTouch Action
    @objc func fromTouchTapped(_ sender: UITapGestureRecognizer) {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "ViewControllerB")
        viewController.modalTransitionStyle = .crossDissolve
        let navController = UINavigationController(rootViewController: viewController)
        present(navController, animated: true, completion: nil)
    }
Bhavesh Nayi
  • 3,626
  • 1
  • 27
  • 42
jackios
  • 155
  • 2
  • 11

3 Answers3

0

First B should have a delegate variable that points to A. This means their must be a direct connection such as A is the parent of B.

Another easy solution if there is no direct connection between A and B is to use Notification Center. Where B generates an event and A Add observer to that event. You can follow this example: Using Notification Center In Swift

Mahmoud Fayez
  • 3,398
  • 2
  • 19
  • 36
0

Your ViewController A looks ok, but seems you did not set ViewController B's delegate variable, do it once you launch ViewController B, like so:

viewControllerA.present(viewControllerB, animated: true)
viewControllerB.delegate = viewControllerA // notice this line

Since you are within the instance of viewControllerA, replace viewControllerA with self

full delegation example below

protocol IsAbleToReceiveData: class {
    func pass(data: String)  //data: string is an example parameter
}

class ViewControllerA: UIViewController, IsAbleToReceiveData {

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(frame: CGRect(x: 15, y: 100, width: 0, height: 0))
        button.addTarget(self, action: #selector(launchAction), for: .touchUpInside)
        button.setTitle("Launch ViewController B", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.sizeToFit()
        self.view.addSubview(button)
    }

    @objc func launchAction() {
        let viewController = ViewControllerB() // guard let viewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB else { return }
        viewController.delegate = self
        self.present(viewController, animated: true)
    }

    func pass(data: String) {
        print("Received Data: \(data)")
    }

}

class ViewControllerB: UIViewController {

    weak var delegate: IsAbleToReceiveData?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .white

        let button = UIButton(frame: CGRect(x: 15, y: 100, width: 0, height: 0))
        button.addTarget(self, action: #selector(exitAction), for: .touchUpInside)
        button.setTitle("Exit ViewController B", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.sizeToFit()
        self.view.addSubview(button)
    }

    @objc func exitAction() {
        self.delegate?.pass(data: "Hello World!")
        self.dismiss(animated: true)
    }

    func pass(data: String) {
        print("Received Data: \(data)")
    }

}
AamirR
  • 11,672
  • 4
  • 59
  • 73
  • I am bit confused. I updated my question please check above. ViewController A to B then B to A movement happening in my app. ViewController B to A time I need to pass value from B to A.@AamirR – jackios Apr 26 '19 at 05:06
  • Check the update and sample project https://github.com/r-aamir/delegates_delegation – AamirR Apr 26 '19 at 05:24
  • Thank you for your Awesome sample code answer. its working and more helpful.@ AamirR – jackios Apr 26 '19 at 05:27
0

Everything is right you missed assign delegate in your ViewControllerA while present ViewControllerB.

if let VC_B = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB{
    VC_B.delegate = self
    VC_B.modalTransitionStyle = .crossDissolve
    self.present(VC_B, animated: true, completion: nil)
}

Note

let viewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB

instad of

let viewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerB")

Nikunj Kumbhani
  • 3,758
  • 2
  • 26
  • 51
  • If I give that, I am getting Error: Value of type 'UIViewController' has no member 'delegate'. @Nikunj Kumbhani – jackios Apr 26 '19 at 04:55
  • @jackios Please check you ViewControllerB class name and you need to put this in MyViewController while present. – Nikunj Kumbhani Apr 26 '19 at 04:56
  • @jackios Please add your **ViewcontrollerB** Class name and code of present controller from **MyViewController** in question because you getting this error due to getting ViewController as a UIViewController while present but if you want to pass anything then you need to get Controller via Class name. – Nikunj Kumbhani Apr 26 '19 at 05:07
  • ViewcontrollerB.delegate = self if I add before present viewcontrollerB in Viewcontroller A, I am getting Error: Instance member 'delegate' cannot be used on type 'ViewcontrollerB' @Nikunj Kumbhani – jackios Apr 26 '19 at 05:09
  • @jackios What is the Class name of your second ViewController here you write wrong code for a present that's why getting an error? – Nikunj Kumbhani Apr 26 '19 at 05:11
  • thank you buddy. working now. @ Nikunj Kumbhani – jackios Apr 26 '19 at 05:19
  • Thank you for your answer. its working and more helpful. @ Nikunj Kumbhani – jackios Apr 26 '19 at 05:27