【问题标题】:Updating a Tab Bar badge count from Push Notification when the app is in the foreground当应用程序处于前台时,从推送通知更新选项卡栏徽章计数
【发布时间】:2019-10-26 11:02:58
【问题描述】:

我的 TabBarController 中有一个通知选项卡,我想显示与应用程序徽章计数相同的徽章计数。除了应用程序在前台时,我让它在所有情况下都能正常工作。

为此,我为我的 TabBarController 创建了一个自定义类,该类注册 UIApplicationWillEnterForeground 通知并将通知选项卡的徽章设置为等于应用程序徽章。我也在 OnLoad() 函数中执行此操作。

现在,当应用程序已在前台时,如何更新通知选项卡徽章?我在 AppDelegate 函数中捕获了通知:

    application(_:didReceiveRemoteNotification:fetchCompletionHandler:)

我知道 可能可以在 rootViewController 周围挖掘以找到选项卡栏控制器,但我的根控制器是我的应用程序的入口点,它检查用户是否在钥匙串和连接到登录视图控制器或标签栏控制器。所以考虑到它继续我不确定这是一个选择吗?

我的 UI 是否可以像我注册接收 UIApplicationWillEnterForeground 通知的方式一样注册“推送通知”通知?这将是理想的,但我还没有设法找到这样的通知。

任何建议或提示将不胜感激!

【问题讨论】:

    标签: ios swift uitabbarcontroller


    【解决方案1】:

    AppDelegate 中发布来自didReceiveRemoteNotification 的通知,并在您的自定义TabBarController 中添加一个观察者来监听和更新UI,如下所示,

    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
            return true
        }
    
        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
            NotificationCenter.default.post(Notification(name: Notification.Name("didReceiveNotification")))
        }
    }
    
    class TabBarController: UITabBarController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            NotificationCenter.default.addObserver(
                self,
                selector: #selector(updateBadgeCount),
                name: Notification.Name(rawValue: "didReceiveNotification"),
                object: nil
            )
        }
    
        @objc private func updateBadgeCount() {
            // Update badge count
        }
    
        deinit {
            NotificationCenter.default.removeObserver(self)
        }
    }
    

    【讨论】:

    • 谢谢!我一直在寻找内置的通知类型。我没想过要检查是否可以发布自己的自定义通知。这非常有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2019-09-06
    • 2012-04-02
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多