在 Xcode 8.3 上将徽章图标添加到 iOS 10

Adding badge icon to iOS 10 on Xcode 8.3

这是我的 AppDelegate(由 Xcode 8.3 的开发人员制作,iOS10),它可以完美地发送通知,但我想在我的 [=21] 中添加徽章=]仪表板。

我尝试添加 application.applicationBadgeNumber = XX,但 XX 永远不会更新,无论是否有 5 个新通知或 none(此时应删除徽章),它都会保持在 XX 上。

如何使徽章图标正确流动以显示应用中是否有新通知?

import UIKit
import Firebase
import IQKeyboardManagerSwift
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
 let gcmMessageIDKey = "gcm.message_id"

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


        // Override point for customization after application launch.

   //     UINavigationBar.appearance().barTintColor = UIColor.black
       UINavigationBar.appearance().tintColor = UIColor(red:0.00, green:0.81, blue:1.00, alpha:1.0)
        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor(red:0.00, green:0.81, blue:1.00, alpha:1.0)]//[NSForegroundColorAttributeName:UIColor.white]



        /*

        let navBackgroundImage:UIImage! = UIImage(named: "background.png")
        UINavigationBar.appearance().setBackgroundImage(navBackgroundImage, for: .default)

        UINavigationBar.appearance().tintColor = UIColor.black
*/

        UITabBar.appearance().tintColor = UIColor(red:0.00, green:0.81, blue:1.00, alpha:1.0)

        UITabBar.appearance().barTintColor = UIColor(red:0.98, green:0.98, blue:0.98, alpha:1.0)

        FIRApp.configure()
        IQKeyboardManager.sharedManager().enable = true


        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(self.tokenRefreshNotification),
                                               name: .firInstanceIDTokenRefresh,
                                               object: nil)






        let storyboard = self.grabStoryboard()
        // display storyboard
        self.window!.rootViewController! = storyboard.instantiateInitialViewController()!
        self.window!.makeKeyAndVisible()

        return true
    }

    func grabStoryboard() -> UIStoryboard {
        // determine screen size
        let screenHeight = UIScreen.main.bounds.size.height

        print ("screen : \(screenHeight)")
        var storyboard: UIStoryboard?
        switch screenHeight {
        // iPhone 4s
        case 480:
            print("ici iphone4")
            storyboard = UIStoryboard(name: "iphone4", bundle: nil)
        // iPhone 5s
        default:
            // it's an iPad
            print("ici default")
            storyboard = UIStoryboard(name: "Main", bundle: nil)
        }

        return storyboard!
    }



    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.
        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }

    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.
        connectToFcm()


    }

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

        // FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .un)

        // FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .unknown)


        let chars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
        var token = ""

        for i in 0..<deviceToken.count {
            token += String(format: "%02.2hhx", arguments: [chars[i]])
        }

        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)

        print("Device Token = ", token)


    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Did Fail to Register for Remote Notifications")
        print("\(error), \(error.localizedDescription)")
    }



    func tokenRefreshNotification(_ notification: Notification) {


        if let refreshedToken = FIRInstanceID.instanceID().token() {
            //      constantsApp.user.deviceToken = refreshedToken
            print("InstanceID token: \(refreshedToken)")
        }
        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }



    func connectToFcm() {
        FIRMessaging.messaging().connect { (error) in
            if (error != nil) {
                print("Unable to connect with FCM. \(error ?? "" as! Error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }

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

    // [START receive_message]
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification
        // With swizzling disabled you must let Messaging know about the message, for Analytics
        // Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)
    }



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

        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification
        // With swizzling disabled you must let Messaging know about the message, for Analytics
        // Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print message ID.
        // Print full message.

        print(userInfo)

        completionHandler(UIBackgroundFetchResult.newData)
    }
    // [END receive_message]
  }




@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        // Print message ID.
        print("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)
    }

    @available(iOS 10, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("Userinfo \(response.notification.request.content.userInfo)")
        //    print("Userinfo \(response.notification.request.content.userInfo)")
    }
}

extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        print("%@", remoteMessage.appData)
    }
}

对于iOS 10:

您需要在您的 AppDelegate 中实施 UserNotifications。

import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

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

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
        if error != nil {
            //
        }
    }
    return true

}

那么你可以这样做:

let content = UNMutableNotificationContent()
content.badge = 10 // your badge count

老 iOS:

let badgeCount: Int = 123
let application = UIApplication.sharedApplication()

if #available(iOS 7.0, *) {
    application.applicationIconBadgeNumber = badgeCount
}

if #available(iOS 8.0, *) {
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Badge], categories: nil))
    application.applicationIconBadgeNumber = badgeCount
}

if #available(iOS 9.0, *) {
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Badge], categories: nil))
    application.applicationIconBadgeNumber = badgeCount
}