Problems like this are way harder than you might think. Consider this sequence:
The user sets a timer for 30 minutes from now.
Then they move your app to the background.
iOS suspends your app.
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"