How do I schedule notifications with UNUserNotificationCenter in Swift?

Scheduling notifications in Swift using UNUserNotificationCenter allows you to send alerts, reminders, and other notifications to users. Here's how you can set up local notifications step by step.

Keywords: Swift, UNUserNotificationCenter, local notifications, schedule notifications, iOS development
Description: Learn how to use UNUserNotificationCenter to schedule local notifications in Swift. This guide provides an example to help you get started with iOS push notifications.

import UserNotifications

// Request permission to display alerts and play sounds.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, error in
    if granted {
        print("Permission granted")
    } else {
        print("Permission denied")
    }
}

// Create a new notification content
let content = UNMutableNotificationContent()
content.title = "Reminder"
content.body = "This is your scheduled notification."
content.sound = UNNotificationSound.default

// Configure a time-based trigger (e.g., 5 seconds from now)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

// Create the request for the notification
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

// Add the request to the notification center
UNUserNotificationCenter.current().add(request) { error in
    if let error = error {
        print("Error adding notification: \(error.localizedDescription)")
    }
}
    

Keywords: Swift UNUserNotificationCenter local notifications schedule notifications iOS development