在后台重新加载推送通知徽章

时间:2017-02-26 10:45:08

标签: ios push-notification swift3 badge

我正在使用xcode 10中的swift3创建通知服务。 现在的问题是,当推送通知进入后台时(即使应用程序关闭),徽章最初不会增加,而是从第二次推送通知增加1。 此外,当我进入应用程序并返回后台时,徽章的数量将是正常的,但上述问题将再次发生。

我试图通过延迟或本地通知检查问题,但我无法弄清问题是什么。

以下是与AppDelegate中的通知相关的通知。推送通知点击事件也可以正常工作。

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

1 个答案:

答案 0 :(得分:0)

在后台状态下运行应用程序只是暂停应用程序暂停的方式。暂停时,应用程序仍保留在内存中,但不执行任何代码。因此,您的代码未执行,因此徽章值不会更新。请参阅以下链接,了解有关应用程序状态和后台执行的信息。

解决此问题的更好方法是在推送通知有效负载内发送发送徽章值。 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服务。

我建议更改推送通知有效负载。

感谢。

相关问题