我使用 ionic 来创建适用于 iOS 和 Android 的应用程序。 我通过 google Firebase 在 ionic 中使用推送通知(从本教程获得的说明https://ionicframework.com/docs/native/push-notifications) 这在 Android 上工作得很好,调用了这个回调,并且我使用以下代码将令牌存储在后端:
PushNotifications.addListener('registration',
(token: Token) => {
console.debug('token is: ' + token.value + ', user.mobileToken is: ' + user.mobileToken + ' in PushNotifications.addListener#registration');
if(user.mobileToken != null && user.mobileToken != token.value) {
this.authService.getUser().then(response => {
user.mobileToken = token.value;
this.userService.updateUser(user).subscribe(response => {
const updatedUser = response;
const message = 'mobile token is stored in backend for user ' + user.title + ' ' + user.firstname + ' ' + user.surname;
this.toastService.presentToast('bottom', message, 500);
console.debug(message + ' in PushNotifications.addListener#registration');
});
}, error => {
console.log(error);
});
}
}
);
对于 iOS,显然需要在 Xcode-AppDelegate.swift 中添加以下内容:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
print("AppDelegate#application first:", deviceToken.map { String(format: "%02x", $0) }.joined())
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
}
我在 Xcode 控制台中得到的输出是 AppDelegate#应用程序优先:
639f6c0f86e74db0aaab6889832ad040f00e9e590319a513bacc1579a968f954
此令牌与上面我使用 PushNotifications.addListener('registration', ... 得到的令牌相同)
本教程进一步https://firebase.google.com/docs/cloud-messaging/ios/receive?hl=de提到必须在 AppDelegate.swift 中添加以下代码:
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(String(describing: 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.
}
}
因此,使用此代码也会生成一个令牌,例如
fcPGyQDykEP7nvC5k6-JIJ:APA91bEwQ7biKli9LaP4NrB_s3aqzD2iKw7wXc58_OrrN_m3v5zlFjFcWiFX9CUqij-JOppOKwkuh-g60lETrHdt7I9o2yHJXMT8crp7
因此生成的代币完全不同,只有第二个 FCN 代币有效,上面的第一个代币不起作用。 我现在的问题是如何解决这个问题。我真的必须再次在后端存储第二个令牌吗?
您的第一个代码片段获取一个标识当前用户的 ID 令牌(来自
this.authService.getUser()
)。
您的最后一个代码片段获取标识设备的 FCM 设备令牌(来自
messaging... didReceiveRegistrationToken
)。
这些代币具有不同的含义和目标,并且不能互换使用。
如果您想在 JavaScript 中获取令牌,请使用 Firebase 云消息传递文档中描述的流程来访问注册令牌。从快速 search on ionic get fcm token 看来你也可以通过调用
getToken()
的 FCMPlugin
函数在 Ionic 中获得它。