Dave
Dave

Reputation: 12216

Run Code Every Time App Opens - Better Way?

I need code to run every time the app opens, including if it was only suspended (user hit home button, then returned to app).

I already know that viewDidLoad only loads on the initial VC load, so that doesn't do what I need. And viewWillAppear / viewDidAppear don't do it either. This SO thread has an answer but it's from six years ago and I don't love the answer. Essentially, it says create an observer. However, that seems like a waste of resources and observers create those reference loops that keep things in memory.

If no one gives me a better solution I might try "applicationDidBecomeActive" in the AppDelegate, but I try not to load my appDelegate up with ViewController code.

My question is, in the six years since this SO thread was answered, do Swift/iOS10 now allow for a cleaner solution?

Upvotes: 1

Views: 1455

Answers (2)

Dave
Dave

Reputation: 12216

As far as I can tell after additional research, there's no new way since that post six years ago. However, the applicationDidBecomeActive approach does work well:

func applicationDidBecomeActive(_ application: UIApplication) {
    guard let rvc = self.window?.rootViewController as? firstVCName else { return }
    rvc.nameOfMethodYouWantToCall()
}

The above gets a reference to the existing VC (instead of creating a whole new instance). Then it calls the method, without having to load up the appDelegate with code. Very simple and efficient.

I tested this and it's exactly what I needed, code that runs every time the app is opened. It's very consistent.

Upvotes: 2

tejas
tejas

Reputation: 187

If you don't want to use NSNotificationCenter Than make global object of your Viewcontroller in AppDelegate

and put code in applicationDidBecomeActive with your viewController object

Because applicationDidBecomeActive calls everyTime when you start your application and when you press home button and came from background so you don't need to write your code in viewWillAppear.

Upvotes: 6

Related Questions