0
0
iOS Swiftmobile~20 mins

Local notifications in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Notification Scheduler
This screen lets users schedule a local notification that will appear after 5 seconds when they tap a button.
Target UI
-------------------------
| Notification Scheduler |
-------------------------
|                       |
|   [ Schedule Alert ]   |
|                       |
-------------------------
Add a button labeled 'Schedule Alert' centered on the screen.
When tapped, request notification permission if not already granted.
Schedule a local notification to appear after 5 seconds with title 'Reminder' and body 'This is your local notification!'.
Handle permission denial gracefully by showing an alert.
Use UserNotifications framework.
Starter Code
iOS Swift
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()
    }
}
Task 1
Task 2
Task 3
Task 4
Solution
iOS Swift
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.

Final Result
Completed Screen
-------------------------
| Notification Scheduler |
-------------------------
|                       |
|   [ Schedule Alert ]   |
|                       |
-------------------------
User taps 'Schedule Alert' button.
App requests notification permission if not granted.
If permission granted, a notification appears after 5 seconds with title 'Reminder' and body 'This is your local notification!'.
If permission denied, an alert pops up explaining the denial.
Stretch Goal
Add a toggle to enable or disable notifications and save the preference.
💡 Hint
Use @AppStorage to save the toggle state and check it before scheduling notifications.