After taking appropriate permissions for the background notifications in your app and adopting UNUserNotificationCenterDelegate in the appropriate viewController. You can implement this method to trigger notifications in the background and take actions to perform any action from the notification. To perform any action from the notification you need to adopt the function userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
.
func startNotifications() {
let notificationCenter = UNUserNotificationCenter.current()
// to include any action in the notification otherwise ignore it.
let action = UNNotificationAction(identifier: "ActionRelatedIdentifier", title: "Name which you want to give", options: [.destructive, .authenticationRequired])
let category = UNNotificationCategory(identifier: "CategoryName", actions: [stopAction], intentIdentifiers: [], options: [])
notificationCenter.setNotificationCategories([category])
let content = UNMutableNotificationContent()
content.title = "Your Title"
content.body = "Message you want to give"
content.sound = UNNotificationSound.default
// To trigger the notifications timely and repeating it or not
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1.5, repeats: false)
content.categoryIdentifier = "CategoryName"
print("Notifications Started")
let request = UNNotificationRequest(identifier: "NotificationRequestIdentifier", content: content, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: { (error) in
if error != nil {
print("Error in notification : \(error)")
}
})
}
Disclaimer: do apply the solution according to your need and ask if anything wrong happens. This code is for triggering background notifications.