如何在 iOS 推送通知上增加徽章

Anu*_*han 5 push-notification badge ios swift2

我目前正在从有效载荷中获取徽章。但是我怎样才能更新那个值。

{"aps":
    {"alert":"Notification Hub test notification2",
     "badge":1,
     "sound":"Default"}
}
Run Code Online (Sandbox Code Playgroud)

当我发送它时,它总是在徽章编号中显示 1,但是当我进入应用程序并退出时,它会得到更新。正是因为这个,

func applicationDidBecomeActive(application: UIApplication) {
        UIApplication.sharedApplication().applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
    }
Run Code Online (Sandbox Code Playgroud)

但是当我发送新的推送通知时,它再次在图标中显示 1 作为徽章编号。我应该怎么做,据我所知,我应该在发送有效载荷时发送更新的徽章。为此,我必须处理后端。

除了这个之外还有什么建议可以处理内部应用程序吗?

小智 7

如果你的项目有一个通知扩展,你可以在里面做徽章设置。

首先启用应用程序组并从应用程序通知服务扩展中保存您的徽章计数UserDefaults. 我们正在使用应用程序组,因为我们需要从AppDelegate打开应用程序时清除徽章计数。您也可以bestAttemptContent.badge从通知服务扩展中设置徽章的值

在通知服务扩展中:

if let userDefaults = UserDefaults(suiteName: "group.com.bundle.appname") {

    let badgeCount = userDefaults.integer(forKey: "badgeCount")
    if badgeCount > 0 {
        userDefaults.set(badgeCount + 1, forKey: "badgeCount")
        bestAttemptContent.badge = badgeCount + 1 as NSNumber
    } else {

        userDefaults.set(1, forKey: "badgeCount")
        bestAttemptContent.badge = 1
    }
}
Run Code Online (Sandbox Code Playgroud)

在 AppDelegate 中,您可以清除徽章...并将徽章的值设置为用户默认值为零

if let userDefaults = UserDefaults(suiteName: "group.com.bundle.appname") {
    userDefaults.set(0, forKey:"badgecount")
}
UIApplication.shared.applicationIconBadgeNumber = 0
Run Code Online (Sandbox Code Playgroud)


chi*_*ure 6

我会给你我的方式:

我的计划是使用 KVO 来听 [UIApplication sharedApplication].applicationIconBadgeNumber

- (void)setupBadgeOperation {
    [[UIApplication sharedApplication] addObserver:self forKeyPath:@"applicationIconBadgeNumber" options:NSKeyValueObservingOptionNew context:nil];
}
Run Code Online (Sandbox Code Playgroud)

一旦值发生变化,我会[[NSNotificationCenter defaultCenter] postNotificationName:STATUS_BADGENUMBER_CHANGED object:nil]用来通知 UI 需要修改徽章的位置。

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *, id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"applicationIconBadgeNumber"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:STATUS_BADGENUMBER_CHANGED object:nil];
    }
}
Run Code Online (Sandbox Code Playgroud)

接收远程通知更改[UIApplication sharedApplication].applicationIconBadgeNumber.

一种。应用程序是前台
b. 应用程序是背景
c. 应用程序未启动

在 a 和 b 的情况下,将调用此方法:

- (void)application:(UIApplication *)application
    didReceiveRemoteNotification:(NSDictionary *)userInfo
          fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    void(^tapBlock)(void(^completeHandler)()) = ^(void(^completeHandler)()) { 
    // here I remove some code not related with the question
    NSNumber *badgeNumber = userInfo[@"aps"][@"badge"];
    [UIApplication sharedApplication].applicationIconBadgeNumber = badgeNumber.integerValue;
} 
Run Code Online (Sandbox Code Playgroud)

在c的情况下,没有办法获得回调,所以我会手动完成。

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] postNotificationName:STATUS_BADGENUMBER_CHANGED object:nil];
}
Run Code Online (Sandbox Code Playgroud)

这就是全部,对我来说效果很好。


Ahm*_*iah 6

这是我的方式斯威夫特:

1) 启动应用程序后,您需要将徽章(一个您可以随意调用的变量)设置为零到 Firebase 实时数据库中。加上设置 application.applicationIconBadgeNumber = 0。这是我在 AppDelegate 中的做法:

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    application.applicationIconBadgeNumber = 0

    // Reset badge number to zero
    let userID = Auth.auth().currentUser?.uid

    let dbRef = Database.database().reference()
    dbRef.child("Users Info").child(userID!).updateChildValues(["badge":"0"], withCompletionBlock: { (err, ref) in
        if err != nil {
            print(err!)
            return
        }
    })

}
Run Code Online (Sandbox Code Playgroud)

2) 转到触发函数的 index.js。

...
return admin.database().ref('/Users Info/' + owner).once('value', snapshot => {

    var ownerValue = snapshot.val();

    var badgeNumber = parseInt(ownerValue.badge) + 1;

    // Notification details.
    const payload = {
      notification: {
        title: 'You have a new request!',
        body: `A new request from ${downedBy.name}.`,
        badge:`${badgeNumber}`,
        sound: 'default',
      }
    };
    ...
    ...
    // Upload the new value of badge into Firebase to keep track of the number
    return admin.database().ref('/Users Info/' + owner).update({badge:badgeNumber});
    ...
    })
Run Code Online (Sandbox Code Playgroud)


Vis*_*ane -3

你正朝着正确的方向前进。您必须从有效负载中更新徽章编号,这是推送通知中的标准方式。

  • 这是评论,不是答案。 (3认同)