swift ios - 如何从 AppDelegate 在 ViewController 中运行函数 [英] swift ios - How to run function in ViewController from AppDelegate
问题描述
我正在尝试使用 AppDelegate
func applicationDidBecomeActive(_ application: UIApplication) {
ViewController().grabData()
}
但不知何故,当从后台进入应用程序后应用程序变为活动状态时,该功能似乎根本没有运行.
But somehow the function does not seem to run at all when the app has become active after entering the app from the background.
函数看起来像这样
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 money: Double = 0.000
我错过了什么?
谢谢!
推荐答案
ViewController().grabData()
将创建一个新的 ViewController 实例并调用这个函数.然后......由于视图控制器未使用,它将被垃圾收集/从内存中删除.您需要在正在使用的实际视图控制器上调用此方法.不是它的新实例.
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.
最好的选择是监听 iOS 提供的 UIApplicationDidBecomeActive
通知.
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)
确保你也移除了观察者,这通常是在 deinit
方法中完成的
make sure that you also remove the observer, this is usually done in a deinit
method
deinit() {
NotificationCenter.default.removeObserver(self)
}
这篇关于swift ios - 如何从 AppDelegate 在 ViewController 中运行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!