0

我想在 userdefault 中存储一个值以在选项卡项上显示徽章值。当应用程序处于前台和后台状态时,代码工作正常。但它不会在非活动状态下将值存储在 userdefault 中。因此,当我启动应用程序时,我无法在应用程序终止后收到收到的通知计数。

在类中添加以下代码AppDelegate

public static var badgeValue: String? {
    get {
        return UserDefaults.standard.string(forKey: "updateBadgeValue")
    }
    set(newValue) {
            UserDefaults.standard.set(newValue, forKey: "updateBadgeValue")
            UserDefaults.standard.synchronize()
    }
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if let badgeValue = AppDelegate.badgeValue {
        AppDelegate.badgeValue = String(Int(badgeValue)!+1)
    } else {
        AppDelegate.badgeValue = "1"
    }
NotificationCenter.default.post(name: NSNotification.Name("updateBadgeValue"), object: nil)
}

并通过类中的以下代码获取值UITabBarController

 override func viewDidLoad() {
    super.viewDidLoad()

    updateBadgeValue()
}

func updateBadgeValue() {
    if UIApplication.shared.applicationIconBadgeNumber != 0 {
        self.tabBar.items![0].badgeValue = String(UIApplication.shared.applicationIconBadgeNumber)
    }
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name("updateBadgeValue"), object: nil). 
    NotificationCenter.default.addObserver(self, selector: #selector(updateBadgeValue), name: NSNotification.Name("updateBadgeValue"), object: nil)
}

//移除观察者正在移除之前添加的观察者,以便之前添加的观察者会一次又一次地调用。如果我不删除观察者,那么当我进入 UITabBarController 类时,它每次都会添加新的观察者。

4

0 回答 0