How to display notification with custom appearance in SwiftUI (using notification content extension)

337 Views Asked by At

I am trying to implement iOS notifications with a custom appearance following this documentation/tutorial. It involves creating a notification extension.

I am still new to this concept of custom iOS notifications and notification extensions, and I can't figure out how to display or test these custom notifications (this app is written in SwiftUI). Any help would be appreciated.

I have gotten default notifications working as expected using the following code. I'd like to follow this structure (for the custom notifications) if possible:

func testNotification() { //called in .onAppear()
     let content = UNMutableNotificationContent()
     content.title = "AppName Tracking"  //replace this with custom notification
     content.subtitle = "Don't forget to track your health" //replace this with custom notification
     content.sound = UNNotificationSound.default

     // show this notification 10 seconds from call
     let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
     let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

     UNUserNotificationCenter.current().add(request)
}

Edit: Here is my AppDelegate and application function:

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
        FirebaseApp.configure()
        return true
    }
}
1

There are 1 best solutions below

2
IT-Guy007 On

Please share your appdelegate, specially the following:

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

As this handles the incoming.

If it is for background only, share the following:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

Make sure you have asked for permissions, otherwise it wouldn't work either.