How to generate a Combine Publisher for didReceiveRemoteNotification?

Viewed 243

I am trying to generate a Combine publisher off didReceiveRemoteNotification

Similar to this code below:

NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)

I want to use SwiftUI Lifecycle and don't want to use AppDelegate methods using @UIApplicationDelegateAdaptor

1 Answers

There is no Notification named didReceiveRemoteNotification, but you can declare it in an extension on UIApplication:

extension UIApplication {
    static let didReceiveRemoteNotification = Notification.Name("didReceiveRemoteNotification")
}

Then you need to post the Notification from the AppDelegate:

extension AppDelegate {
    
    func application(_ application: UIApplication,
                     didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
        NotificationCenter.default.post(name: UIApplication.didReceiveRemoteNotification,
                                        object: nil)
        
        // etc...
    }
    
}

That will allow you to use the usual syntax:

NotificationCenter.default.publisher(for: UIApplication.didReceiveRemoteNotification)
Related