my view controller has many initialized methods and variables. When my app enters background, I need to access a particular value in view controller from app delegate.
I have tried to do this in app delegate:
vc = ViewController()
...but that makes a new instance, and values are essentially set as new.
You have two options, the second one is better by design.
First option: (what you want)
I don't know the structure of your view controllers, so let me assume you have a root view controller, you could get it from AppDelegate
via:
rootVC = self.window?.rootViewController
And if you want to get the presented view controller from the root view controller (like many apps, the presented view controller is a tab bar controller):
guard let tabBarController = rootVC.presentedViewController as? TabBarController else {
return
}
Once you get your tab bar controller, you can find the view controller in the array of view controllers:
tabBarController.viewControllers
Essentially, what I'm trying to say is you have to jump through your view controllers starting from the root to get to the controller you want, then grab the variable from there. This is very error prone, and generally not recommended.
Second option (better practice):
Have your view controller register as an observer for the UIApplicationWillResignActiveNotification
notification. This will allow you to do whatever you want from the view controller when your app is about to enter background.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With