簡體   English   中英

測試(Firebase)FCM

[英]Testing (Firebase) FCM

為了了解如何使用Firebase Cloud Messaging ,我正在關注以下文檔: https : //firebase.google.com/docs/cloud-messaging/admin/send-messages?hl= Firebase Cloud Messaging

恰好我正在查看此部分: 發送到各個設備

我在代碼中看到我需要一個registrationToken 我的問題是我具體如何得到一個?

我首先想將消息發送到我自己的iPhone,放在我的桌子上,然后再發送給所有注冊用戶的iPhone。

當我在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

使用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();

暫無
暫無

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

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