swift ios - How to run function in ViewController from AppDelegate

后端 未结 2 1905
情深已故
情深已故 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)
    } 
    

提交回复
热议问题