How to update application badge count locally in iOS swift

How to update badge count locally in ios swift :

In this tutorial, we will learn how to update the badge count of an iOS application using Swift. Badge count is the count number that is displayed with your application icon on home page.

Actually, this count number should be displayed using a push notification instead of handling it manually after the app starts. Image a scenario, you have one email application and this count shows you the number of unread emails. How do you want to update the count?

  1. The application is in the background or killed, one silent notification is sent to the application and it automatically updates the new email count on the application icon.
  2. User opens the application and new email count is updated.

Method 1 is more valuable than method 2. But after the user will read the unread emails, we need to again update the count . But this time no notification will be received. We will update it locally. In this example, we are going to learn how to update the count locally. I will publish one different article on how to update the count using notification. Let’s write some code :

Swift: how to update badge count :

  1. You need one active Apple Developer Program Membership plan and your app should be configured using the same account on xCode.
  2. Go to project editor and Move to the Capabilities tab. Here, enable the Push Notifications tab.
  3. That’s it. Now change the AppDelegate.swift file as below :
import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        if #available(iOS 9, *) {
            UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
            UIApplication.shared.registerForRemoteNotifications()
        }
        
        else if #available(iOS 10, *) {
            UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
            application.registerForRemoteNotifications()
        }

        return true
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        UIApplication.shared.applicationIconBadgeNumber = 5
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        
    }
    

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

Run the application. On start, it will ask the user to allow push notification service as below :

Screen Shot 2018 01 04 at 10 32 27 PM

After user will allow it , func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)_ method will be called. Here, we are setting the value of the badge count. You can set the value of badge count on anywhere you want. It will update the badge count on home screen.