Search code examples
iosswifttimer

Swift - Timer doesn't stop


I have the following code:

class firstVC: UIViewController {
    var timer : Timer?

    func scheduledTimerWithTimeInterval(){
        timer = Timer.scheduledTimer(timeInterval: 60, target: self, 
        selector: #selector(self.anotherFunc), userInfo: nil, repeats: 
        true)
    }

    override func viewDidAppear(_ animated: Bool) {
        scheduledTimerWithTimeInterval()
    }
}

I'm trying to stop the timer without success:

func stopTimer() {
    if timer != nil {
        timer?.invalidate()
        timer = nil
    }
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    stopTimer()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    stopTimer()
}

I even tried to put the stop function in applicationWillResignActive And in applicationDidEnterBackground but it didn't stop:

firstVC().stopTimer()

Your help will be appreciated, thank you.


Solution

  • 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()
    
        }
    

    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()
        }