------------------------- | Notification Scheduler | ------------------------- | | | [ Schedule Alert ] | | | -------------------------
Local notifications in iOS Swift - Mini App: Build & Ship
import SwiftUI import UserNotifications struct ContentView: View { var body: some View { VStack { // TODO: Add Schedule Alert button here } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color.white) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
import SwiftUI import UserNotifications struct ContentView: View { @State private var showingPermissionAlert = false @State private var alertMessage = "" var body: some View { VStack { Button("Schedule Alert") { scheduleNotification() } .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color.white) .alert(isPresented: $showingPermissionAlert) { Alert(title: Text("Notification Permission"), message: Text(alertMessage), dismissButton: .default(Text("OK"))) } } func scheduleNotification() { let center = UNUserNotificationCenter.current() center.getNotificationSettings { settings in switch settings.authorizationStatus { case .notDetermined: center.requestAuthorization(options: [.alert, .sound]) { granted, error in DispatchQueue.main.async { if granted { sendNotification() } else { alertMessage = "Permission was denied. Please enable notifications in settings." showingPermissionAlert = true } } } case .authorized, .provisional: DispatchQueue.main.async { sendNotification() } case .denied: DispatchQueue.main.async { alertMessage = "Permission was denied. Please enable notifications in settings." showingPermissionAlert = true } default: break } } } func sendNotification() { let content = UNMutableNotificationContent() content.title = "Reminder" content.body = "This is your local notification!" content.sound = UNNotificationSound.default let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) { error in if let error = error { DispatchQueue.main.async { alertMessage = "Failed to schedule notification: \(error.localizedDescription)" showingPermissionAlert = true } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
This solution uses SwiftUI and the UserNotifications framework to schedule a local notification.
The button labeled Schedule Alert triggers scheduleNotification(). This function first checks the current notification permission status.
If permission is not determined, it requests authorization. If granted, it schedules the notification; if denied, it shows an alert.
If permission is already authorized or provisional, it schedules the notification immediately.
If permission is denied, it shows an alert informing the user.
The notification is set to fire after 5 seconds with a title and body as required.
Alerts are shown using SwiftUI's .alert modifier bound to state variables.
------------------------- | Notification Scheduler | ------------------------- | | | [ Schedule Alert ] | | | -------------------------
Practice
Solution
Step 1: Understand user permission requirement
iOS requires apps to ask users for permission before sending notifications to respect privacy.Step 2: Request permission before scheduling
You must call the requestAuthorization method to get user consent before scheduling any notifications.Final Answer:
Request permission from the user to send notifications -> Option AQuick Check:
Permission request = Request permission from the user to send notifications [OK]
- Scheduling notifications without permission
- Assuming notifications work without user consent
- Skipping the requestAuthorization call
Solution
Step 1: Identify the correct class for notification content
UNMutableNotificationContent is the class used to create and customize notification content.Step 2: Differentiate from other classes
UNNotificationContent is abstract and cannot be instantiated; UNNotificationRequest is for scheduling, not content.Final Answer:
let content = UNMutableNotificationContent() -> Option CQuick Check:
Use UNMutableNotificationContent() to create content [OK]
- Trying to instantiate UNNotificationContent directly
- Confusing UNNotificationRequest with content
- Using wrong class names
let content = UNMutableNotificationContent() content.title = "Reminder" content.body = "Time to drink water" let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let request = UNNotificationRequest(identifier: "waterReminder", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request)
Solution
Step 1: Analyze the trigger setup
The trigger is set with timeInterval 5 seconds and repeats false, so it fires once after 5 seconds.Step 2: Understand notification scheduling
The request is added to the notification center, so the notification will appear after the delay with the specified title and body.Final Answer:
A notification appears after 5 seconds with the given title and body -> Option AQuick Check:
TimeInterval trigger fires once after delay = A notification appears after 5 seconds with the given title and body [OK]
- Thinking repeats false means no notification
- Assuming notification appears immediately
- Confusing repeats true with repeats false behavior
let content = UNMutableNotificationContent() content.title = "Alert" let trigger = UNTimeIntervalNotificationTrigger(timeInterval: -10, repeats: false) let request = UNNotificationRequest(identifier: "alert1", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request)
Solution
Step 1: Check the trigger timeInterval value
The timeInterval is set to -10, which is invalid because it must be positive.Step 2: Understand trigger constraints
UNTimeIntervalNotificationTrigger requires a positive timeInterval to schedule the notification correctly.Final Answer:
Negative timeInterval causes an error; timeInterval must be positive -> Option BQuick Check:
timeInterval > 0 required = Negative timeInterval causes an error; timeInterval must be positive [OK]
- Using negative or zero timeInterval
- Ignoring permission request (though important, not error here)
- Confusing title and body properties
Solution
Step 1: Understand daily repeating notification needs
To trigger at a specific time daily, use UNCalendarNotificationTrigger with repeats true and matching hour and minute.Step 2: Compare options
UNTimeIntervalNotificationTrigger(timeInterval: 86400, repeats: true) repeats every 86400 seconds but may drift; UNCalendarNotificationTrigger(dateMatching: DateComponents(hour: 8, minute: 0), repeats: true) correctly uses calendar components for 8:00 AM daily; UNCalendarNotificationTrigger(dateMatching: DateComponents(hour: 8, minute: 0), repeats: false) does not repeat; UNTimeIntervalNotificationTrigger(timeInterval: 3600, repeats: true) repeats every hour, not daily.Final Answer:
UNCalendarNotificationTrigger(dateMatching: DateComponents(hour: 8, minute: 0), repeats: true) -> Option DQuick Check:
Use calendar trigger with repeats true for daily time [OK]
- Using time interval triggers for exact daily time
- Setting repeats false for repeating notifications
- Confusing seconds with hours in timeInterval
Ready to prove it?
Pass the test and this pattern moves unknown
