【问题标题】:Testing (Firebase) FCM测试 (Firebase) FCM
【发布时间】:2018-12-01 01:46:22
【问题描述】:

为了了解如何使用Firebase Cloud Messaging,我正在关注这个文档: https://firebase.google.com/docs/cloud-messaging/admin/send-messages?hl=en-us

正是我在看这个部分:发送到单个设备

我可以在代码中看到我需要一个registrationToken。我的问题是如何具体得到一个?

我首先想向我自己的 iPhone 发送一条消息,然后放在我的办公桌上,然后再发送给所有注册用户的 iPhone。

【问题讨论】:

    标签: javascript firebase firebase-cloud-messaging


    【解决方案1】:

    当我在 IOS-Swift 中工作时,你必须在你的 AppDelegate.swift 文件中添加这个方法:

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

    如果您需要直接访问令牌,请使用:

    InstanceID.instanceID().instanceID { (result, error) in
       if let error = error {
          print("Error fetching remote instange ID: \(error)")
       } else if let result = result {
         print("Remote instance ID token: \(result.token)")
         self.instanceIDTokenMessage.text  = "Remote InstanceID token: \(result.token)"
       }
      }
    

    欲了解更多信息,请访问:

    https://firebase.google.com/docs/cloud-messaging/ios/client

    【讨论】:

    • 我已经尝试过你的建议,我可能做错了事,但似乎从未调用过函数 messing:didReceiveRegistrationToken 。你对这个问题有什么想法吗?
    • 在网上搜索后,我发现我在执行所有步骤时没有遵循正确的顺序。与此同时,你给了我一个宝贵的建议。非常感谢。另一个帖子github.com/firebase/firebase-ios-sdk/issues/1339 帮助我解决了这个问题。
    【解决方案2】:

    在使用 FCM 通知时,设备会生成令牌,这些令牌会经常更新,因此如果您需要向设备发送推送,您必须知道您的令牌,您必须实现一个继承 FirebaseMessagingService 的类,并覆盖onNewToken 方法,每次更新设备令牌时都会在后台调用该方法。

    /**
    * Called if InstanceID token is updated. This may occur if the security of
    * the previous token had been compromised. Note that this is called when the     InstanceID token
    * is initially generated so this is where you would retrieve the token.
    */
    @Override
    public void onNewToken(String token) {
    Log.d(TAG, "Refreshed token: " + token);
    
        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(token);
    }
    

    建议将此令牌发送到您的服务器,以便您可以从那里将推送发送到已注册令牌的设备。如果要强制使用第一个令牌,可以使用:

    FirebaseInstanceId.getInstance().getInstanceId();
    

    【讨论】:

    • 你的代码不是 Swift,我正在使用一个用 Swift 编写的 iOS 应用程序。我会尝试在 Swift 中找到对应的函数。
    猜你喜欢
    • 2018-06-21
    • 1970-01-01
    • 2019-11-23
    • 2021-04-23
    • 2017-05-04
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多