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

时间:2017-09-16 17:23:10

标签: ios swift xcode icons badge

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

我尝试添加application.applicationBadgeNumber = XX,但XX永远不会更新,无论是否有5个新通知或者没有(此时应删除徽章),它都会保留在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)
    }
}

1 个答案:

答案 0 :(得分:1)

适用于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
}
相关问题