简体   繁体   中英

Push Notifications are getting cleared from Notification center, when Setting applicationIconBadgeNumber in Background mode

I am downloading my events in background mode, for that I will receive a push and a silent Notification. As I have to download data when my app is in background mode, so I am using silent notification for downloading data through a web service and before that I am updating applicationIconBadgeNumber based on an increment value. When I am updating applicationIconBadgeNumber with my auto increased value all my push notifications are getting cleared in notification center. If I am not setting any applicationIconBadgeNumber they are remaining same. As I have posted my code below, please do let me know if I am missing out something.

var autoIncrementForNotification:Int = 0


func  application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UIApplication.shared.setMinimumBackgroundFetchInterval(60)

    if #available(iOS 10, *) {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {(accepted, error) in
            if !accepted {
                print("Notification access denied.")
            } else {

                application.registerForRemoteNotifications()
            }
        }
    } else {

        application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
    }

    return true

}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

    UserDefaults.standard.removeObject(forKey: "Device_Token")
    UserDefaults.standard.setValue(deviceTokenString, forKey: "Device_Token")

}



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

    let aps = userInfo["aps"] as! [String: AnyObject]
    if ((aps["content-available"] as? NSString)?.integerValue == 1)
    {
        let type = (aps["type"] as? NSString)

        if(type == Constants.action_type_Events)
        {
            if (application.applicationState == .inactive || application.applicationState == .background)
            {
                autoIncrementForNotification += 1
                application.applicationIconBadgeNumber = autoIncrementForNotification

              // Firing my Web service
                completionHandler(UIBackgroundFetchResult.newData)

            }

        }

    }

}

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void){

    completionHandler(UIBackgroundFetchResult.newData)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("i am not available in simulator \(error)")
}

func  applicationDidBecomeActive(_ application: UIApplication) {

    application.applicationIconBadgeNumber = 0
    autoIncrementForNotification = 0


}

Please try the following :

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

    let aps = userInfo["aps"] as! [String: AnyObject]
    if let content = aps["content-available"] as? String {
        contentAvailable = Int(content)!
    } else {
        contentAvailable = aps["content-available"] as! Int
    }

    if (contentAvailable == 1)
    {
        let type = (aps["type"] as? NSString)

        if(type == Constants.action_type_Events)
        {
            if (application.applicationState == .inactive || application.applicationState == .background)
            {
                autoIncrementForNotification += 1
                application.applicationIconBadgeNumber = autoIncrementForNotification

                // Firing my Web service
                completionHandler(UIBackgroundFetchResult.newData)

            }

        }

    }

}

Reason :

If your Payload file is like this {"aps":{"content-available":1}} below condition is not satisfying, so everytime applicationIconBadgeNumber is becoming 0

if ((aps["content-available"] as? NSString)?.integerValue == 1) 

If your Payload file is like this {"aps":{"content-available":"1"}} then your code will work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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