E
E
Emil2021-05-14 23:11:21
Swift
Emil, 2021-05-14 23:11:21

How to keep "counting the timer" when the user has hidden the app or opened something else?

Greetings!
I have a timer that, every tick, changes a certain parameter that is responsible for the graphical representation of the remaining time (filling with color BackGround View)

@objc func fireTimer() {
        
        
        
            self.Wave.progress += (100/(self.TimeForCook! * 100000))
            print(self.Wave.progress)
       
    
    }
    
    func StartTimer() {
        TimeForCook = 10
        Timer1 = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)
        DispatchQueue.main.asyncAfter(deadline: .now() + TimeInterval(TimeForCook)) {
            print("It's ready")
            self.Timer1?.invalidate()
        }
       
    }

Everything works fine, but as soon as I hide it, changing the parameters stops.
DispatchQueue.main.asyncAfter(deadline: .now() + TimeInterval(TimeForCook)) {
            print("It's ready")
            self.Timer1?.invalidate()
        }

Works.
Question:
How can I keep track of the time that has passed since hiding and resuming the application, and based on this adjust the state of the timer graphic display?
Thanks in advance to those who respond.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg, 2021-05-14
@DyadyaEmil

If it does not work, then you are not solving the problem correctly.
Firstly, the timer should always beep at the right time.
Otherwise, the pizza will burn or the kettle will boil away.
This is the first task.
To solve it, you need "completion time"
The second task is to actually color your background.
Background coloring should be called in onResume and start the periodic call timer there.
we store two times. Beginning, end.
We take the current one.
interval = endTime-startTime;
cur = curTime-startTime;
percent = 100*cur/interval;
Well, the cries of "Chief, everything is lost" if the first task did not work out.
And you don't need 0.001 so often. UI is enough and 10 times per second.

B
briahas, 2021-05-15
@briahas

Read about BackgroundTasks .
In short - (I did it a long time ago, I can mess up the details) you need to start the timer as BackgroundTasks. And, let's say, we show a notification when the timer is over, and we are still in the background mode.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question