2 min read
Step 5: Notifications
Send local notifications when the timer completes.
Where We Are
The timer works and sessions switch automatically. But if your phone is locked or you’re in another app, you won’t know the timer finished. Let’s fix that.
Request Permission
When the app launches, request notification permissions:
- Import UserNotifications
- Call UNUserNotificationCenter.current().requestAuthorization
- Request .alert, .sound, and .badge
- Handle the case where the user denies permission gracefully
Do this once when the app first opens.
Schedule a Notification
When the timer starts, schedule a local notification:
- Set it to fire after the remaining seconds
- Title: "Time's up!" (or "Break's over!" for break sessions)
- Body: "Your focus session is complete. Time for a break."
(or "Break is over. Ready to focus?" for breaks)
- Play the default sound
When the timer is paused or reset, cancel any pending notifications.
Use UNUserNotificationCenter to manage scheduled notifications.
Handle App Background
The Timer stops when the app goes to the background.
To handle this:
- Save the end time (Date) when the timer starts
- When the app comes back to foreground, calculate how much time passed
- Update remaining seconds based on actual elapsed time
- If the time already expired while backgrounded, trigger the completion
Use .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification))
to detect when the app returns.
Test It
- Start a timer with a short duration (1 minute)
- Lock your phone or switch to another app
- Wait for the notification to appear
- Tap the notification — it should open your app
- Test pausing — notification should not fire
- Test reset — notification should be cancelled
Checkpoint
By now you should have:
- Notification permission requested on first launch
- Notification fires when timer completes
- Different messages for focus and break sessions
- Pending notifications cancel on pause/reset
- Timer syncs correctly after backgrounding
What You Learned
- UNUserNotificationCenter for local notifications
- Scheduling and cancelling notifications
- Handling app lifecycle (background/foreground)
- Time-based calculations with Date