swift ios – 如何从AppDelegate在ViewController中运行函数

我试图使用AppDelegate在某些ViewController运行一个函数

 func applicationDidBecomeActive(_ application: UIApplication) { ViewController().grabData() } 

但不知何故,当应用程序从后台进入应用程序后变为活动状态时,该function似乎根本无法运行。

该function看起来像这样

 func grabData() { self._DATASERVICE_GET_STATS(completion: { (int) -> () in if int == 0 { print("Nothing") } else { print(int) for (_, data) in self.userDataArray.enumerated() { let number = Double(data["wage"]!) let x = number!/3600 let z = Double(x * Double(int)) self.money += z let y = Double(round(1000*self.money)/1000) self.checkInButtonLabel.text = "\(y) KR" } self.startCounting() self.workingStatus = 1 } }) } 

并使用此var

 var money: Double = 0.000 

我错过了什么?

谢谢!

ViewController().grabData()将创建ViewController的新实例并调用此函数。 然后..由于视图控制器未被使用,它将被垃圾收集/从内存中删除。 您需要在正在使用的实际视图控制器上调用此方法。 不是它的新实例。

最好的选择是监听iOS提供的UIApplicationDidBecomeActive通知。

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

确保你也删除了观察者,这通常是以deinit方法完成的

 deinit() { NotificationCenter.default.removeObserver(self) } 

我简单地解决了这个问题:

 func applicationDidBecomeActive(_ application: UIApplication) { let viewController = self.window?.rootViewController as! ViewController viewController.grabData() } 

创建两个全局变量,例如var instance: Viewcontroller?var flag = 0然后在你的viewDidLoad函数中设置实例变量为self像这样: instance = selfflag = 1

现在您已准备好使用此Controller的任何function,如下所示:

  func applicationDidBecomeActive(_ application: UIApplication) { if flag == 1 { instance.grabData() } } 

也许它需要一个? 在实例之后(我现在不在我的Mac上所以我无法测试它)如果它需要它只是添加它。

希望能帮助到你。

编辑:

要使全局变量只在class之前添加行

flag是为了避免在第一次启动时运行该function