且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift - 计时器不会停止

更新时间:2023-12-04 08:37:52

经过研究我找到了解决方案,
唯一对我有用的是在 AppDelegate 文件中创建函数并在需要时调用它们,
下面是代码,timerSwitch 函数:

After research I found a solution,
The only thing that worked for me is to create functions in AppDelegate file and call them when needed,
Here is the code, the timerSwitch function:

    func timerSwitch()
    {
        if (timerStatus) {
            checkStateTimer = Timer.scheduledTimer(
                timeInterval: 60, 
                target:self, 
                selector: #selector(self.yourFunction), 
                userInfo: nil, repeats: true)
        } else {
            checkStateTimer?.invalidate()
        }
    }

    func stopTimer()
    {
        timerStatus = false
        timerSwitch()

    }

    func startTimer()
    {
        timerStatus = true
        timerSwitch()

    }

虽然 'yourFunction' 是您想要在计时器启动时执行的内容,
在我的情况下是发送心跳.
然后我在AppDelegate中调用的timerSwitch就是下面的函数:

While 'yourFunction' is what you want to execute when the timer starts,
In my case is sending heartbeat.
Then I called the timerSwitch is the following functions in AppDelegate:

    func applicationWillResignActive(_ application: UIApplication) {
        stopTimer()
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        stopTimer() 
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        startTimer()
    }