收到fcm推送通知时设置应用徽章

时间:2018-03-13 09:55:25

标签: ios swift push-notification firebase-cloud-messaging badge

我正在使用FCM进行云消息传递。我想在后台和前台应用程序状态下从服务器收到推送通知时添加应用程序徽章。我错过了什么?主要问题是根据推送通知添加/更新/删除应用程序徽章,我可以接收和处理推送消息。我有3天这个问题。请帮帮我 !? *徽章编号根据内部内容而变化,例如,如果收到gmail应用程序的新电子邮件,徽章编号会更改为后台应用程序状态和前台应用程序状态中未尝试的邮件计数。

使用XCode 9.2,swift 3.2,iOS 11.6

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

    FirebaseApp.configure()
    var fcmtoken: String = ""

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

    if let token = Messaging.messaging().fcmToken {
        fcmtoken = token
        print("FCM token: \(fcmtoken)")
    } else {
        print("FCM token: \(fcmtoken) == no FCM token")
    }

    return true
}

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")

    Messaging.messaging().subscribe(toTopic: "all")
    print("subscribed to all topic in didReceiveRegistrationToken")

    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
}


func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
    Messaging.messaging().subscribe(toTopic: "all")
    print("subscribed to all topic in notificationSettings")
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {

    print("userInfo -- \(userInfo)")

}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    let userInfo = response.notification.request.content.userInfo
    print("user info in didReceive response -- \(userInfo)")

}


@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    print("called to foreground app")
}

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

    Messaging.messaging().subscribe(toTopic: "all")
    print("subscribed to all topic in didRegisterForRemoteNotificationsWithDeviceToken")
}

1 个答案:

答案 0 :(得分:7)

有效负载是您的内容:

我们刚刚做的很多事情都取代了本地通知中的触发器。通知的内容可在有效负载中找到。回到测试平台,你会发现:

{"aps":{"alert":"Enter your message","badge":1,"sound":"default"}}

理想情况下,您的JSON文件应如下所示。你的有效载荷只有4K,所以在空间上浪费它是不受欢迎的。发送有效负载时避免使用空格。但是,他们很难以这种方式阅读。它看起来更像这样:

{
 "aps":{
        "alert":"Enter your message",
        "badge":1,
        "sound":"default"
 }
}

aps是一个JSON字典,其中包含描述您内容的条目。警报条目可以是类似于此处的字符串,也可以是描述设备上显示的警报内容的字典。徽章给出了徽章图标上显示的数字。声音播放默认声音。您可以修改此有效负载以更改警报中显示的内容。由于警报可以是字典或字符串,因此您可以向其添加更多内容。将有效负载更改为:

{
 "aps":{
        "alert":{
                "title":"Push Pizza Co.",
                "body":"Your pizza is ready!"
         },
            "badge":42,
            "sound":"default"
 }
}

这将添加标题和关于您的披萨准备就绪的消息。它还会将徽章更改为42

{"aps":{"alert":{"title":"Push Pizza Co.","body":"Your pizza is ready!"},"badge":42,"sound":"default"}}

enter image description here

通知显示标题和正文。徽章的编号为42。

但是,您也可以在应用处于活动状态时进行更改。您需要通过注册UserNotificationType来获得用户的许可。获得许可后,您可以将其更改为您希望的任何数字。

  application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
    UIUserNotificationType.Badge, categories: nil
    ))

application.applicationIconBadgeNumber = 5

你也可以这样做:

  let badgeCount: Int = 10
    let application = UIApplication.shared
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
    }
    application.registerForRemoteNotifications()
    application.applicationIconBadgeNumber = badgeCount

结果:

enter image description here

备注: 请检查以下徽章的应用权限: enter image description here

参考: https://makeapppie.com/2017/01/03/basic-push-notifications-in-ios-10-and-swift/