lhy
lhy

Reputation: 51

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.

Upvotes: 4

Views: 2148

Answers (1)

CryptoAlgorithm
CryptoAlgorithm

Reputation: 1034

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

Upvotes: 4

Related Questions