project focustimer
Step 5: Notifications
System Text-to-Speech Ready
Slide: 0:00 / 0:00
Slide 1 of 0Interactive Deck
Full Lesson Reference
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
terminal
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
terminal
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 soundterminal
When the timer is paused or reset, cancel any pending notifications.
Use UNUserNotificationCenter to manage scheduled notifications.Handle App Background
terminal
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
Exercises
- Wire up permission requests and scheduling, then start a 1-minute timer, switch to another app, and confirm the notification appears with the correct focus-session message.
- Verify cancellation: start a timer, then pause and reset, and confirm no notification fires for the cancelled session.
- Test backgrounding sync — start a timer, leave the app for 30 seconds, return, and confirm the remaining time reflects the actual elapsed time rather than freezing.