[英]swift ios - How to run function in ViewController from AppDelegate
I am trying to run a function in certain ViewController
using AppDelegate
我试图使用
AppDelegate
在某些ViewController
运行一个函数
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. 但不知何故,当应用程序从后台进入应用程序后变为活动状态时,该功能似乎根本无法运行。
The function looks like this 该功能看起来像这样
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
}
})
}
And uses this var 并使用此var
var money: Double = 0.000
What have I missed? 我错过了什么?
Thanks! 谢谢!
ViewController().grabData()
will create a new instance of the ViewController and call this function. ViewController().grabData()
将创建ViewController的新实例并调用此函数。 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. 最好的选择是监听iOS提供的
UIApplicationDidBecomeActive
通知。
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
方法完成的
deinit() {
NotificationCenter.default.removeObserver(self)
}
I simply solved it like this: 我简单地解决了这个问题:
func applicationDidBecomeActive(_ application: UIApplication) {
let viewController = self.window?.rootViewController as! ViewController
viewController.grabData()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.