ios - 使用 firebase 云消息传递中的 swift 无法将通知接收到 iPhone

标签 ios swift firebase firebase-cloud-messaging apple-push-notifications

我想使用 Firebase 云消息传递将通知从我的应用程序发送到另一个应用程序。因此,我在该过程中使用了这个方法retrieveFCMToken(forSenderID: senderid)。我将这段代码添加到我的应用程序委托(delegate)中:

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

    let senderid = "<YOUR SENDER ID>"
    Messaging.messaging().retrieveFCMToken(forSenderID: senderid) {(message,Error) in  
        print("message",message!)
    }
}

这是我的应用程序委托(delegate):

import UIKit
import UserNotifications

import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

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

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

        FirebaseApp.configure()

        // [START set_messaging_delegate]
        Messaging.messaging().delegate = self
        // [END set_messaging_delegate]
        // Register for remote notifications. This shows a permission dialog on first run, to
        // show the dialog at a more appropriate time move this registration accordingly.
        // [START register_for_notifications]
        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()

        // [END register_for_notifications]
        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[gcmMessageIDKey] {
            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[gcmMessageIDKey] {
            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)")
        Messaging.messaging().apnsToken = deviceToken

        //Code for sending to other sender ID
        let senderid = "xxxxxxxx"
        Messaging.messaging().retrieveFCMToken(forSenderID: senderid) {(message,Error) in  // here i am generating the token for other sender id project
            print("message",message!)
        }
    }
}

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

我遵循了这种情况:我有两个应用程序,即“A”和“B”。我想将通知从应用程序“A”发送到应用程序“B”。因此,我将应用程序 A 的发件人 ID 放入应用程序 B 委托(delegate)文件中,并使用应用程序 B 生成应用程序 A 的注册 token 。因此,我将生成的注册 token 放置在应用程序 A 的 firebase 云消息传递控制台中,同时将通知发送到应用程序 B .但是应用程序B没有收到通知。如何解决这个错误?我在 Firebase 云消息传递的两个应用程序数据库中上传了有效的 APN 身份验证 key 。

最佳答案

A 和 B 是两个独立的应用程序,因此,一个的 FCM token 对另一个应用程序无效。每个应用程序都会生成仅与其 Firebase 项目相关的唯一 token 。为了从 A 到 B 或 B 到 A 发送和接收通知,您需要在每个应用程序中配置两个 Firebase 项目,然后检索相应的 FCM token 。之后,您将能够发送和接收通知

关于ios - 使用 firebase 云消息传递中的 swift 无法将通知接收到 iPhone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56863434/

相关文章:

ios - 在 Alamofire 上使用 DisableEvaluation 信任无效证书

ios - 在不同的 View Controller 中打开webkit View

ios - Firebase 在 Swift 3 中处理其中包含字典的子快照

ios - systemLayoutSizeFittingSize : on UILabel not behaving like expected

ios - GoogleMaps 不是 dylib,最新版本的 pod 文件编译时错误

ios - 从其他 VC 调用函数

swift - 如何管理登录时的访问控制

iOS:UITableView 底部的额外空间

arrays - 如何按作为结构​​值包含的数组进行过滤

firebase - 是否可以通过 API 创建新的 Firebase 项目?