0

Is it possible to run a function defined in a view controller from the AppDelegate function applicationWillEnterForeground? If so, how? I am trying to do this in applicationWillEnterForeground but vc is nil.

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
         return true
    }
    
    func applicatioWillEnterForeground (_ application: UIApplication) {
        
        if let vc = window?.rootViewController as? ViewController {
             vc.resetValues()
    }

}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
DumbBlonde
  • 58
  • 6
  • 2
    That could work indeed, if the `rootViewController` is `ViewController`, but maybe it's simpler to listen to the Notification willEnterForeground inside `ViewController` and call `resetValues()`. See https://stackoverflow.com/questions/25716012/triggering-a-specific-action-when-the-app-enters-foreground-from-a-local-notific notification which in recent Swift version has been renamed: https://developer.apple.com/documentation/uikit/uiapplication/1622944-willenterforegroundnotification – Larme Oct 02 '21 at 16:32
  • By the way, be very careful in the method names. Note the typo in `applicatioWillEnterForeground`. Probably just a type introduced when composing the question, but FWIW… – Rob Oct 02 '21 at 16:57
  • I think this may work to fix the problem! – DumbBlonde Oct 02 '21 at 18:56

0 Answers0