iOS Notifications

Below is code for creating a notification locally on iOS, and triggering it 5 seconds later.

import SwiftUI
import UserNotifications

struct ContentView: View {
    var body: some View {
        Button("Trigger Notification") {
            let content = UNMutableNotificationContent()
            content.title = "Hello"
            content.subtitle = "World"
            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 {
                    print("Error: \(error.localizedDescription)")
                } else {
                    print("Notification scheduled!")
                }
            }
        }
    }
}

Don’t forget to request permissions to send notifications.

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
    if let error = error {
         print("Error: \(error.localizedDescription)")
    } else {
         scheduleNotification()
    }
}