Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement SwiftUI Notifications

I am trying to implement notifications in my SwiftUI app, but have not managed to do so after extensive research on Google and other search engines.

like image 752
lhy Avatar asked Oct 22 '25 07:10

lhy


1 Answers

Here's a simple example on how to use notifications in a SwiftUI app. It requests for permissions and checks if they are granted, and allows you to send a notification if so.

Do note that notifications from apps won't appear if the app they originate from is in the foreground, so I demonstrate closing the app quickly before the notification is sent to view it.

Here's the whole example code the demo uses:

import SwiftUI
import UserNotifications

struct ContentView: View {
    @State private var permissionGranted = false

    private func requestPermissions() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
            if success {
                permissionGranted = true
            } else if let error = error {
                print(error.localizedDescription)
            }
        }
    }

    private func sendNotification() {
        let notificationContent = UNMutableNotificationContent()
        notificationContent.title = "Hello world!"
        notificationContent.subtitle = "Here's how you send a notification in SwiftUI"

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        // you could also use...
        // UNCalendarNotificationTrigger(dateMatching: .init(year: 2022, month: 12, day: 10, hour: 0, minute: 0), repeats: true)

        let req = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: trigger)

        UNUserNotificationCenter.current().add(req)
    }

    var body: some View {
        VStack {
            if !permissionGranted {
                Button("Request Permission") {
                    requestPermissions()
                }
            }

            if permissionGranted {
                Button("Send Notification") {
                    sendNotification()
                }
            }
        }
        .onAppear {
            // Check if we already have permissions to send notifications
            UNUserNotificationCenter.current().getNotificationSettings { settings in
                if settings.authorizationStatus == .authorized {
                    permissionGranted = true
                }
            }
        }
        .padding()
    }
}

Demo video

like image 75
CryptoAlgorithm Avatar answered Oct 26 '25 05:10

CryptoAlgorithm