首页 > 解决方案 > iOS 设备上未收到 Firebase 推送通知。虽然控制台记录了消息,但它在设备上收到

问题描述

我根据 Firebase 控制台中提供的说明创建了一个示例 ios 应用程序,以在 ios 设备上接收云消息。通知消息从控制台发送并打印在应用程序控制台上。但是即使在给予必要的许可后,设备也不会收到推送通知。

我正在使用 swift 3 和 xCode 10.3 版。在 Firebase 控制台中注册了应用程序,并通过应用程序接收所需的 FCM 令牌并添加以向设备发送测试消息。尝试通过控制台发送大量消息,但设备上均未显示。它显示消息正在控制台上成功发送。

以下是我为接收推送通知而编写的 AppDelegate.swift 文件。

import UIKit
import UserNotifications
import Firebase
import FirebaseMessaging
import FirebaseInstanceID

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

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

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

        if #available(iOS 10.0, *) {

            FirebaseApp.configure()           

            Messaging.messaging().delegate = self
            Messaging.messaging().shouldEstablishDirectChannel = true

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


        // request permission from user to send notification
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { authorized, error in
            if authorized {
                DispatchQueue.main.async(execute: {
                    application.registerForRemoteNotifications()
                })
            }
            else{
                print("Notification access denied")
            }
        })
        return true
    }


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

        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        print(userInfo)
    }

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

        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        print(userInfo)

        completionHandler(UIBackgroundFetchResult.newData)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Unable to register for remote notifications: \(error.localizedDescription)")
    }


    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
        print("APNs token retrieved: \(deviceToken)")


    }

}

@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(userInfo)
         print("Message ID: \(userInfo["gcm.message_id"]!)")
        completionHandler(UNNotificationPresentationOptions.alert)

    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        print("Do what ever you want")
        // Print full message.
        print("tap on on forground app",userInfo)


        completionHandler()
    }
}

extension AppDelegate : MessagingDelegate {

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")
        Messaging.messaging().subscribe(toTopic: "/topics/nutriewell_live")
        Messaging.messaging().shouldEstablishDirectChannel = true

    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")
    }


}

我希望在 ios 设备上收到推送通知,但我没有收到任何通知。我得到以下输出,它与从控制台发送的通知消息一起打印。

2019-08-15 11:20:32.548066+0530 FirebaseIos[800:207059]  - <AppMeasurement>[I-ACS036002] Analytics screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. 




To disable screen reporting, set the flag FirebaseScreenReportingEnabled to NO (boolean) in the Info.plist



2019-08-15 11:20:32.949393+0530 FirebaseIos[800:207068] 6.2.0 - [Firebase/Messaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. If you'd prefer to manually integrate Firebase Messaging, add "FirebaseAppDelegateProxyEnabled" to your Info.plist, and set it to NO. 


Firebase registration token: fsyB51mCvbg:APA91bFvRFPIxauHfKA-v-K29YTWl_TYFTgCpnvODrFA2rG8qN-F8vcLIWcZ-lOChkJw-pIBVhcxg2epBz7AYVALMNLC4Hs6M4ds_pQXytYymjr15KMqOt08_7PkmYkU1jHy6xcw5hvx
2019-08-15 11:20:34.914040+0530 FirebaseIos[800:207059] 6.2.0 - [Firebase/Messaging][I-FCM002024] Format '/topics/nutriewell_live' is deprecated. Only 'nutriewell_live' should be used in subscribeToTopic.
Notification access denied


2019-08-15 11:20:48.869741+0530 FirebaseIos[800:207068] [BoringSSL] nw_protocol_boringssl_get_output_frames(1301) [C7.1:2][0x101537e10] get output frames failed, state 8196




Received data message: [AnyHashable("notification"): {
    body = "firebase ios";
    e = 1;
    tag = "campaign_collapse_key_3627158360856700759";
    title = "firebase!";
}, AnyHashable("from"): 591363996390, AnyHashable("collapse_key"): com.combank.Firebase.Ios]
%@ [AnyHashable("notification"): {
    body = "firebase ios";
    e = 1;
    tag = "campaign_collapse_key_3627158360856700759";
    title = "firebase!";
}, AnyHashable("from"): 591363996390, AnyHashable("collapse_key"): com.combank.Firebase.Ios]





    Received data message: [AnyHashable("collapse_key"): com.combank.Firebase.Ios, AnyHashable("from"): 591363996390, AnyHashable("notification"): {
        body = "firebase ios";
        e = 1;
        tag = "campaign_collapse_key_750970355066402639";
        title = "firebase!";
    }]




%@ [AnyHashable("collapse_key"): com.combank.Firebase.Ios, AnyHashable("from"): 591363996390, AnyHashable("notification"): {
    body = "firebase ios";
    e = 1;
    tag = "campaign_collapse_key_750970355066402639";
    title = "firebase!";
}]




2019-08-15 11:22:34.475335+0530 FirebaseIos[800:207131] [BoringSSL] nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x1015273f0] get output frames failed, state 8196

我可以在这里获得任何帮助吗?

标签: iosswiftfirebasefirebase-cloud-messaging

解决方案


有两种方式接收通知:

  1. 当应用程序关闭/不活动并且您在 didFinishLaunchingWithOptions 中获得有效负载时:

  2. 当应用程序打开/活动且当前可见时,您将在 didReceiveRemoteNotification 中获得有效负载:

当您的应用程序关闭时,iOS 会处理显示通知(如果未开发通知扩展程序)并在您点击它时启动您的应用程序。

如果您的应用程序已打开,您必须注意显示此通知或忽略它。

这是官方文档所说的:

当本地和远程通知不是由您的应用程序或用户直接处理时,它们会显示在通知中心,以便以后查看。使用 共享UNUserNotificationCenter对象的getDeliveredNotificationsWithCompletionHandler:方法获取仍在通知中心显示的通知列表。如果您发现任何现在已过时且不应向用户显示的通知,您可以使用 removeDeliveredNotificationsWithIdentifiers:方法删除它们。

官方文档


推荐阅读