countdown timer in background

hello,

i use Timer for CountDown application,

but it's not working in background !
i want to send local Notification to user the countDown finished and reRun the timer again,

it's like Timer -> end -> (notification) -> restart Timer -> end -> notification

iOS will suspend your app shortly after the user moves it to the background, and that means that your timers won’t run. The best way to handle this scenario:

it's like Timer -> end -> (notification) -> restart Timer -> end ->notification

is to use a local notification.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

thanks for replying,

for more specified :

my app will be like podomoro so when set countDown timer,

i already set localNotification,

but if user re-open the app at any time after fire the timer, would not see the correct elapsed time !


how can i handle it ?

Problems like this are way harder than you might think. Consider this sequence:

  1. The user sets a timer for 30 minutes from now.

  2. Then they move your app to the background.

  3. iOS suspends your app.

  4. The user goes to Settings and moves the time back by an hour.

Does the timer fire after 30 minutes? Or after 90 minutes?

Remember that your app is suspended at step 3, so you can’t write code to adjust the notification. That means that you’re relying on the behaviour of whatever notification API you’re using. If you’re using UserNotifications framework, that comes down to the trigger you use. The obvious choice here is

UNTimeIntervalNotificationTrigger
. Are you using that?

If so, note that it has a

nextTriggerDate
method. My advice is that you grab that and then work backwards from there. That is:
  • When your app is in the foreground, start a timer that runs every second on the second.

  • Invalidate that timer when you’re in the background because it’s not doing anything useful there.

  • When the timer fires, calculate the difference between now and and your notification’s next trigger date and use that to update your UI.

Depending on how time interval triggers respond to time discontinuities this may result in the displayed time bouncing back or forward, but at least it’ll be consistent with the eventual firing of the timer.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
countdown timer in background
 
 
Q