在后台重新加载推送通知徽章
问题描述:
我正在使用xcode 10中的swift3创建通知服务。 现在的问题是,当推送通知在后台出现时(即使应用程序已关闭),徽章不会首先增加,但从第二次推送通知增加1。 此外,当我进入应用程序并在后台回来时,徽章的数量将是正常的,但上述问题将再次发生。在后台重新加载推送通知徽章
我试图通过延迟或本地通知来检查问题,但我一直无法弄清楚问题所在。
下面是与AppDelegate中的通知相关的通知。推送通知Click事件也可以正常工作。
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate, NaverThirdPartyLoginConnectionDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert,], completionHandler: {(granted, error) in
if (granted)
{
application.registerForRemoteNotifications()
}
else{
}
})
return true
}
...
...
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.badge, .alert, .sound])
UIApplication.shared.applicationIconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber + 1
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) {
print("userInfo: \(response.notification.request.content.userInfo)")
var userInfo:[AnyHashable: Any]?
let pushId:Int32 = userInfo?["uid"] as! Int32
self.moveView(pushId)// My app load method
}
}
答
在后台运行应用程序只是暂停应用程序的一个简短的停止。暂停时,应用会保留在内存中,但不会执行任何代码。由于这个原因,你的代码没有执行,因此徽章值不会更新。请参阅下面的链接关于应用程序状态和后台执行。
因此更好的办法来解决这个问题是发送发送推送通知有效载荷的内部徽章价值。 e.g
{
"aps" : {
"alert" : {
"title" : "Game Request",
"body" : "Bob wants to play poker",
"action-loc-key" : "PLAY"
},
"badge" : 5
},
"acme1" : "bar",
"acme2" : [ "bang", "whiz" ]
}
请参阅此链接创建远程通知有效载荷
不要增加徽章值编程,除非你需要显示本地通知徽章。如果您想在推送通知接收时在后台执行代码,请使用VoIP push notification,该限制很少,例如,应用必须与VoIP服务相关。
我建议更改推送通知有效负载。
谢谢。
感谢您的反馈,我很抱歉听到您迟到。让我们快速应用。 –