swift ios - How to run function in ViewController from AppDelegate

后端 未结 2 1906
情深已故
情深已故 2020-12-19 06:32

I am trying to run a function in certain ViewController using AppDelegate

func applicationDidBecomeActive(_ application: UIApplicat         


        
相关标签:
2条回答
  • 2020-12-19 06:53

    ViewController().grabData() will create a new instance of the ViewController and call this function. Then.. as the view controller is not in use it will be garbage collected/removed from memory. You need to be calling this method on the actual view controller that is in use. Not a new instance of it.

    The best option would be to listen for the UIApplicationDidBecomeActive notification that iOS provides.

    NotificationCenter.default.addObserver(
        self,
        selector: #selector(grabData),
        name: NSNotification.Name.UIApplicationDidBecomeActive,
        object: nil)
    

    make sure that you also remove the observer, this is usually done in a deinit method

    deinit() {
        NotificationCenter.default.removeObserver(self)
    } 
    
    0 讨论(0)
  • 2020-12-19 07:10

    I simply solved it like this:

    func applicationDidBecomeActive(_ application: UIApplication) {
            let viewController = self.window?.rootViewController as! ViewController
            viewController.grabData()
    }
    
    0 讨论(0)
提交回复
热议问题