[iOS, SwiftUI] Local Notification on SwiftUI

less than 1 minute read

Request Authorization

UNUserNotificationCenter.current()
    .requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
        if let error = error {
        }
    }

alert

Add a NotificationRequest

UNUserNotificationCenter.current()
    .getNotificationSettings { settings in
        guard settings.authorizationStatus == .authorized else {
            return
        }

        let content         = UNMutableNotificationContent()
            content.title   = "Test Title"
            content.body    = "test message"
            content.sound   = UNNotificationSound.default
            content.badge   = 1
        let dateInfo        = Calendar.current.dateComponents([.weekday, .hour, .minute, .second], from: Date()) // Repeating every week by week
        let trigger         = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
        let request         = UNNotificationRequest(identifier: "identifier", content: content, trigger: trigger)

        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
            }
        }
    }

Notification Trigger

Remove Pending NotificationRequests

UNUserNotificationCenter.current()
    .removePendingNotificationRequests(withIdentifiers: "identifier")

UNUserNotificationCenter.current()
    .removeAllPendingNotificationRequests()

UNUserNotificationCenterDelegate

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            openSettingsFor notification: UNNotification?) {
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {    
    completionHandler()
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    return [.sound, .banner]
}

Reset the badge number

  • must be in main thread
UIApplication.shared.applicationIconBadgeNumber = 0

Source Code

Reference

Leave a comment