如何在 iOS 推送通知上增加徽章 [英] How to do badge increment on iOS push notification

查看:19
本文介绍了如何在 iOS 推送通知上增加徽章的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently getting badge from payload. But how can i update that value.

{"aps":
    {"alert":"Notification Hub test notification2",
     "badge":1,
     "sound":"Default"}
}

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

when i send this it is always shows 1 in the badge number but when i go inside app and exit it's getting updated.It is because of this,

func applicationDidBecomeActive(application: UIApplication) {
        UIApplication.sharedApplication().applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
    }

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

But when i send a new push notification it's again shows 1 as badge number in the icon. How should i do this, to my understand i should send updated badge when i send the payload. For that i have to deal with backend.

除此之外还有其他建议可以处理应用程序内部吗?

Is there any suggestion other than this to handle inside app?

推荐答案

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

If your project has a notification extension, you can do badge setting inside it.

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

First of all enable App Groups and save your badge count from app notification service extension in UserDefaults. We are using app groups because we need to clear badge count from AppDelegate when open app. Also you can set value of badge as bestAttemptContent.badge from notification service extension

在通知服务扩展中:

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
    }
}

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

In AppDelegate you can clear badge...and set value for badge as zero on userdefaults

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

这篇关于如何在 iOS 推送通知上增加徽章的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆