generate a banner notification with a string body in swift

Here's an example code snippet in Swift for generating a banner notification with a string body:

main.swift
import UserNotifications

// Request authorization for notifications
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { granted, error in
    // Handle error and granted values
}

// Create a notification content object
let content = UNMutableNotificationContent()
content.title = "Notification Title"
content.body = "Notification body text"

// Set up a notification request with a trigger
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "notificationIdentifier", content: content, trigger: trigger)

// Add the notification request to the notification center
center.add(request) { error in
    // Handle error
}
749 chars
22 lines

This code imports the UserNotificationsframework and requests authorization for notifications. Then, it creates a UNMutableNotificationContentobject with a title and body text. Finally, it sets up a UNNotificationRequestwith a trigger and identifier, and adds it to the notification center using center.add().

gistlibby LogSnag