收到fcm推送通知时设置应用徽章 [英] Setting app badge when fcm push notifications received

查看:85
本文介绍了收到fcm推送通知时设置应用徽章的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using FCM for cloud messaging. I want to add app badge when I receive a push notification from the server in background and foreground app states. What I'm missing? Main problem is adding/updating/removing app badge according to push notification, I can receive and handle push messages .I'm 3 days on this problem. Help me, please !? * Badge numbers changes according to inside contents, like if new email messages received to gmail app, badge number changes to unreaded message count in both background and foreground app states.

使用XCode 9.2,Swift 3.2,iOS 11.6

using 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")
}

推荐答案

有效载荷就是您的内容:

我们刚才所做的许多事情都替换了本地通知中的触发器.通知的内容可在有效负载中找到.回到测试平台,您会发现:

Much of what we just did replaces the trigger in a local notification. Content for a notification is found in the payload. Going back to the testing platform, you’ll find this:

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

理想情况下,您的JSON文件应如下所示.您只有4K的有效负载,因此在空间上浪费它已成问题.发送有效载荷时,请避免使用空格.但是,很难以这种方式阅读它们.这样看起来更好:

Ideally your JSON file should look like this. You only have 4K for your payload so wasting it on spaces is frowned on. When sending payloads avoid whitespace. However, they are hard to read this way. It looks better like this:

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

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

The aps is a JSON dictionary with entries that describe your content. The alert entry is can be a string like it is here, or a dictionary describing the content of the alert that shows on your device. The badge give the number to show on the badge icon. The sound plays the default sound. You can modify this payload to change the content displayed in the alert. As the alert can be both a dictionary or a string you can add more to it. Change the payload to this:

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

这将添加标题和一条消息,说明您的比萨饼已准备就绪.还将徽章更改为42

This will add a title and a message about your pizza being ready. It will also change the badge to 42

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

出现带有标题和正文的通知.徽章显示为数字42.

The notification appears with the title and body. The badge appears with the number 42.

但是,您还可以在应用程序处于活动状态时对其进行更改.通过注册UserNotificationType,您将需要用户的许可.获得许可后,您可以将其更改为所需的任何数字.

However, you can also change it while your app is active. You will need permission from the user by registering the UserNotificationType. Once you get permission, you can change it to whatever number you wish.

  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

结果:

注释:请检查应用程序许可以获取徽章,例如:

Notes: Please check app permission for badge like :

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

这篇关于收到fcm推送通知时设置应用徽章的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆