swift ios - 如何从AppDelegate在ViewController中运行函数 [英] swift ios - How to run function in ViewController from AppDelegate
问题描述
我试图在 ViewController
中使用 AppDelegate
$运行函数b $ b
func applicationDidBecomeActive(_ application:UIApplication){
ViewController()。grabData()
}
但是某种程度上,当应用程序从后台进入应用程序后,该功能似乎根本无法运行。
函数看起来像这样
func grabData(){
self._DATASERVICE_GET_STATS (完成:如果int == 0 {
print(Nothing)
} else {
print(int)$ b,则
中的{(int) - > $ _ b $ b $ for(_,data)in self.userDataArray.enumerated(){
let number = Double(data [wage]!)
let x = number!/ 3600
let z = Double(x * Double(int))
self.money + = z
让y = Double(round(1000 * self.money)/ 1000)
self.checkInButtonLabel.text =\(y)KR
}
self.startCounting()
self.workingStatus = 1
}
})
}
并使用此变量
var money:Double = 0.000
code>
我错过了什么?
谢谢! > > > > ViewController的新实例并调用此函数。然后,由于视图控制器未被使用,它将被垃圾收集/从内存中移除。您需要在正在使用的实际视图控制器上调用此方法。不是它的新实例。 最好的选择是监听iOS提供的 请确保您还可以移除观察者,这通常在 I am trying to run a function in certain 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 And uses this var What have I missed? Thanks! The best option would be to listen for the make sure that you also remove the observer, this is usually done in a
这篇关于swift ios - 如何从AppDelegate在ViewController中运行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
UIApplicationDidBecomeActive
通知。
NotificationCenter.default.addObserver(
self,
选择器:#selector(grabData),
name:NSNotification.Name.UIApplicationDidBecomeActive,
object:nil)
deinit
方法中完成
$ b $ pre $ deinit(){
NotificationCenter.default.removeObserver(self)
}
ViewController
using AppDelegate
func applicationDidBecomeActive(_ application: UIApplication) {
ViewController().grabData()
}
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()
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. UIApplicationDidBecomeActive
notification that iOS provides. NotificationCenter.default.addObserver(
self,
selector: #selector(grabData),
name: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil)
deinit
methoddeinit() {
NotificationCenter.default.removeObserver(self)
}