【问题标题】:How to generate a Combine Publisher for didReceiveRemoteNotification?如何为 didReceiveRemoteNotification 生成组合发布者?
【发布时间】:2021-02-07 06:40:35
【问题描述】:

我正在尝试从didReceiveRemoteNotification 生成一个组合发布者

类似于下面这段代码:

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

我想使用 SwiftUI 生命周期,不想使用 @UIApplicationDelegateAdaptor 的 AppDelegate 方法

【问题讨论】:

  • 没有。 NotificationCenter.default.publisher(for: UIApplication.didReceiveRemoteNotification) 抛出错误。 => 类型“UIApplication”没有成员“didReceiveRemoteNotification”
  • 收到远程通知时没有发布通知。您需要实现应用委托方法并从那里发送给发布者。

标签: ios swift swiftui combine


【解决方案1】:

没有名为didReceiveRemoteNotificationNotification,但您可以在UIApplication 的扩展中声明它:

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

那么你需要从AppDelegate发布Notification

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

这将允许您使用通常的语法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 2018-11-25
    • 2019-11-30
    • 1970-01-01
    • 2011-02-09
    相关资源
    最近更新 更多