Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access current instance of view controller from app delegate in swift? [duplicate]

Tags:

ios

swift

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.

like image 732
harry lakins Avatar asked May 07 '17 18:05

harry lakins


1 Answers

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.

like image 198
leonardloo Avatar answered Oct 26 '22 23:10

leonardloo