簡體   English   中英

無法將通知發送到iOS(iPhone)Firebase雲消息傳遞

[英]Can Not Send Notification to iOS (iPhone) Firebase Cloud Messaging

Info.plist ,我將FirebaseAppDelegateProxyEnabled添加到NO (boolean) ,並且Background Modes --> Remote Notification功能Background Modes --> Remote Notification處於啟用狀態,而Push Notification也處於啟用狀態。

並在iPhone設備上運行了帶有“允許通知”對話框。

我有一些代碼,例如:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    let gcmBroadcast = "gcm.broadcast"

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


        Messaging.messaging().delegate = self

        // Use Firebase library to configure APIs

        let firebasePListFileName = ControllerEnvironment.getGoogleService()

        let firebaseOptions = FirebaseOptions(contentsOfFile: Bundle.main.path(forResource: firebasePListFileName, ofType: "plist")!)

        FirebaseApp.configure(options: firebaseOptions!)



//        firebase cloud messaging

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

        return true

    }



    // [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[gcmBroadcast] {

            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.

        if let messageID = userInfo[gcmBroadcast] {

            print("Message ID: \(messageID)")

        }

        // Print full message.
        print(userInfo)

        completionHandler(UIBackgroundFetchResult.newData)

    }

    // [END receive_message]

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {

        print("Unable to register for remote notifications: \(error.localizedDescription)")

    }


    // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.

    // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to

    // the FCM registration token.

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

        print("APNs token retrieved: \(deviceToken)")

        // With swizzling disabled you must set the APNs token here.

         Messaging.messaging().apnsToken = deviceToken

    }

}







// [START ios_10_message_handling]

@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


        // With swizzling disabled you must let Messaging know about the message, for Analytics

        // Messaging.messaging().appDidReceiveMessage(userInfo)

        // Print message ID.

        if let messageID = userInfo[gcmBroadcast] {

            print("Message ID: \(messageID)")

        }


        // Print full message.

        print(userInfo)



        // Change this to your preferred presentation option

        completionHandler([])

    }


    func userNotificationCenter(_ center: UNUserNotificationCenter,

                                didReceive response: UNNotificationResponse,

                                withCompletionHandler completionHandler: @escaping () -> Void) {

        let userInfo = response.notification.request.content.userInfo

        // Print message ID.

        if let messageID = userInfo[gcmBroadcast] {

            print("Message ID: \(messageID)")

        }


        // Print full message.

        print(userInfo)


        completionHandler()

    }

}

// [END ios_10_message_handling]


extension AppDelegate : MessagingDelegate {

    // [START refresh_token]

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {

        print("Firebase registration token: \(fcmToken)")


        let dataDict:[String: String] = ["token": fcmToken]

        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)

        // TODO: If necessary send token to application server.

        // Note: This callback is fired at each app startup and whenever a new token is generated.

    }

    // [END refresh_token]

    // [START ios_10_data_message]

    // Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.

    // To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {

        print("Received data message: \(remoteMessage.appData)")

    }

    // [END ios_10_data_message]

}

和日志:

Firebase registration token: f6MUKT270iw:APA9.......Eg
APNs token retrieved: 32 bytes

我嘗試使用Firebase雲消息傳遞控制台將Push發送為: User segment -> app並在消息的Firebase列表中完成了狀態。

但是,實際上我的iPhone沒有收到通知。

我該如何解決這個問題?

在iOS上,該應用程序不必位於前台,否則開發人員會收到推送通知的通知,並可以手動顯示/處理該通知->確保該應用程序不在前台

您還需要向Firebase添加APNs密鑰或APNs證書。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM