iOS FCM未接收到数据消息

时间:2019-09-12 18:09:02

标签: ios swift firebase firebase-cloud-messaging

我正在使用FCM向iOS移动应用发送自定义数据消息,如果有效载荷是这样,我没有收到任何消息:

{
content_available: true,

data : {
    title   : message_title,
    body    : message_body, 
       }
}

但是如果我添加这样的有效负载,我会收到通知:

{
content_available: true,
notification : {
    title   : message_title,
    body    : message_body,         
 },
data : {
    title   : message_title,
    body    : message_body, 
    }
}

但是我不想发送通知,我想发送数据消息。

我的appDelegate是:

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

    FirebaseApp.configure()

    application.registerForRemoteNotifications()

    UNUserNotificationCenter.current().delegate = self
    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in })
    application.applicationIconBadgeNumber = 0

    return true
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken
}

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

    UIApplication.shared.applicationIconBadgeNumber = 0
    let userInfo = notification.request.content.userInfo
    print("[UserNotificationCenter] applicationState: \(applicationStateString) willPresentNotification: \(userInfo)")

    NotificationCenter.default.post(name: .didReceiveData, object: nil, userInfo: userInfo)
}

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

    UIApplication.shared.applicationIconBadgeNumber = 0
    let userInfo = response.notification.request.content.userInfo
    print("[UserNotificationCenter] applicationState--: \(applicationStateString) didReceiveResponse: \(userInfo)")
    completionHandler()
}

为什么数据消息不起作用?

我在此线程https://stackoverflow.com/a/51954446/1747440中找到了解决方案

1 个答案:

答案 0 :(得分:0)

 Messaging.messaging().delegate = self  

Messaging.messaging().shouldEstablishDirectChannel = true

//在didFinishLaunchingWithOptions中调用它,然后检查令牌是否到来

//打印(设备令牌)

///如果仍然没有令牌,则必须确保密钥链中的APNS证书必须位于FireBase云消息传递设置中,除了您的代码看起来还不错,后端设置中只会出现问题,即在Firebase上配置应用程序的方式。

Firebase APNS cer