schedule a notification in swift

To schedule a local notification in Swift, you need to use the UserNotifications framework.

First, import the framework in your ViewController or AppDelegate:

main.swift
import UserNotifications
25 chars
2 lines

Then, request authorization to display notifications:

main.swift
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
    // Handle authorization response
}
150 chars
4 lines

To schedule a notification, create a UNMutableNotificationContent object with the details of your notification (e.g. title, body, sound):

main.swift
let content = UNMutableNotificationContent()
content.title = "My Notification Title"
content.body = "This is my notification message."
content.sound = UNNotificationSound.default
179 chars
5 lines

Next, create a UNCalendarNotificationTrigger or UNTimeIntervalNotificationTrigger object to define when your notification should be triggered. For example, to trigger a notification 30 seconds after scheduling, you could use:

main.swift
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 30, repeats: false)
82 chars
2 lines

To schedule the notification, create a UNNotificationRequest with your content and trigger, and add it to the notification center:

main.swift
let request = UNNotificationRequest(identifier: "myNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
    // Handle any errors from sending the notification
}
218 chars
5 lines

That's it! Your notification should now be scheduled and will trigger at the specified time.

gistlibby LogSnag