简体   繁体   English

收到通知时显示徽章编号

[英]Show badge number when notification received

When notification reach the application, there is no action on badge number. 通知到达应用程序后,将不会对徽章编号进行任何操作。 I set background mode on Capabilities. 我在功能上设置了背景模式。

And there is another problem. 还有另一个问题。 This metod does not invoke when app is background mode. 当应用程序为后台模式时,不会调用此方法。

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print("Push notification received2: \(userInfo)")
    completionHandler(UIBackgroundFetchResult.noData)
}

PS: UIApplication.shared.applicationIconBadgeNumber is not answer. PS:UIApplication.shared.applicationIconBadgeNumber无法回答。 I know that. 我知道。 The problem is even the push notification received by application, the badge number does not update. 问题在于,即使应用程序收到了推送通知,徽章编号也不会更新。

APNS doesn't support increment operations for badges. APNS不支持徽章的增量操作。 each push notification generated should be setting what the current value should be. 生成的每个推送通知都应设置当前值。

so we need to have a service/server somewhere keeping track of what badges should be for each of your users 因此我们需要在某处设置服务/服务器来跟踪每个用户的徽章

for example add the one key of badge in your payload, get the count of your badge and increment the count followed by the example. 例如,在您的有效负载中添加badge的一键,获取徽章的计数,​​并在示例之后增加计数。

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    var currentBadgeNumber: Int = application.applicationIconBadgeNumber
    currentBadgeNumber += Int(userInfo["badge"] as? String ?? "0")!
    application.applicationIconBadgeNumber = currentBadgeNumber
    completionHandler(UIBackgroundFetchResult.noData)
}

for example payload, see the old answer in SO. 例如有效负载,请参阅SO中的旧答案

Note : didReceiveRemoteNotification is deprecated from iOS10+ onwards, see this for example 注意:didReceiveRemoteNotification从iOS10 +开始不推荐使用,请参阅此示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM