我正在从 Firebase 接收带有 APN 的通知的消息。在 Firebase 中,我有 APNs 密钥的证书,与从 Apple Developer 中提取的 Firebase 中的 Xcode 项目中具有相同的 id。
但我不知道为什么会发生这种情况,我收到此错误,它正在消息传递扩展中注册两个令牌:
extension AppDelegate : MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {}}
在检索发件人 ID 的 FCM 令牌之前未设置 APNS 设备令牌 “########”。将不会发送对此 FCM 令牌的通知 通过 APNS。一旦 APNS 设备重新检索 FCM 令牌 令牌已设置。
添加了我在 AppDelegate 中的内容
import Firebase
import MasivPushIosSdk
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate{
var firebaseToken: String = ""
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
self.registerForFirebaseNotification(application: application)
Messaging.messaging().delegate = self
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
func registerForFirebaseNotification(application: UIApplication) {
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()
}
}
extension AppDelegate: MessagingDelegate, UNUserNotificationCenterDelegate {
//MessagingDelegate
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
self.firebaseToken = fcmToken!
print("Firebase token: \(fcmToken)")
}
//UNUserNotificationCenterDelegate
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("APNs received with: \(userInfo)")
}
}
这是模拟器专用的日志。您可以安全地忽略它。您收到此消息的原因是 Firebase 尝试创建从 FCM 令牌到 APNS 令牌的映射,以便它可以将 APNS 消息发送到 iOS 设备。但是,模拟器上没有 APNS 令牌,因此映射失败。
尝试在实际设备上进行测试,看看是否仍然出现错误。
这可能迟到了,但是错误
在检索发件人 ID 的 FCM 令牌之前未设置 APNS 设备令牌 “########”。对此 FCM 令牌的通知将不会通过 APNS。一旦获取 APNS 设备令牌,请务必重新检索 FCM 令牌 已设定。
通过添加此内容为我排序
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("Yay! Got a device token 🥳 \(deviceToken)")
Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
}
我在这个问题上花了很长时间。我终于可以使用远程消息了。
这可能是由几个主要原因造成的。
const authStatus = await firebase.messaging().requestPermission(); if (authStatus === 1) { let fcmToken = await firebase.messaging().getToken(); if (fcmToken) { console.log('Firebase Push Token is:', fcmToken); } }
欲了解更多信息: A) 如果本地工作:https://firebase.google.com/docs/cloud-messaging/ios/client B) 如果使用 React Native:https://rnfirebase.io/messaging/usage/ios-setup
注意:不要混合使用 A 和 B。一个适用于原生 IOS,另一个适用于 React Native。
附注我添加了 React Native,因为我在使用它时在搜索中遇到了你的问题。
确保不要重命名身份验证密钥文件
就我而言,我已将身份验证密钥文件重命名为其他文件,这导致了问题。我尝试将其命名回默认格式
AuthKey_<KeyID>.p8
,一切都开始工作了。
手机/模拟器日志错误
2023-01-28 21:11:53.907821+0100 App[16955:1733197] 10.4.0 - [FirebaseMessaging][I-FCM002022] APNS device token not set before retrieving FCM Token for Sender ID 'XXXXXXXXX'.Be sure to re-retrieve the FCM token once the APNS device token is set.
2023-01-28 21:11:53.908157+0100 App[16955:1733197] 10.4.0 - [FirebaseMessaging][I-FCM002022] Declining request for FCM Token since no APNS Token specified
⚡️ WebView loaded
⚡️ [log] - AppModule, running the app code.
⚡️ [log] -
必须在消息传递组件上设置令牌。
在
AppDelegate.swift
中,您必须有以下处理程序
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
}
按照此说明
Messaging.messaging().apnsToken = deviceToken
完整代码是
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
Messaging.messaging().token(completion: { (token, error) in
if let error = error {
NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
} else if let token = token {
NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: token)
}
})
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
}
Ionic 框架的文档对此进行了解释,详细说明了如何为 iOS 设置 Firebase Messaging。
https://capacitorjs.com/docs/guides/push-notifications-firebase#add-initialization-code
注意 - 通过此设置,通知将在 XCode 和本机设备提供的 iOS 模拟器上工作。
所以,情况是:我们应用程序的
捆绑标识符与我们用来为 Firebase 项目创建 iOS 应用程序的不同。 使它们相同,解决了问题。
在 Pods 文件中:
target 'YOUR APP' do
config = use_native_modules!
pod 'FirebaseCore', :modular_headers => true
pod 'Firebase', :modular_headers => true
pod 'FirebaseMessaging', :modular_headers => true
pod 'FirebaseCoreInternal', :modular_headers => true
pod 'GoogleUtilities', :modular_headers => true
$RNFirebaseAsStaticFramework = true
然后在AppDelegate.h中
#import <UserNotifications/UNUserNotificationCenter.h>
#import <RNFBMessaging+FIRMessagingDelegate.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UIApplicationDelegate,UNUserNotificationCenterDelegate, FIRMessagingDelegate>
@property (nonatomic, strong) UIWindow *window;
然后在AppDelegate.mm中
@实现AppDelegate
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
NSLog(@"FCM registration token: %@", fcmToken);
// Notify about received token.
NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:@"token"];
[[NSNotificationCenter defaultCenter] postNotificationName:
@"FCMToken" object:nil userInfo:dataDict];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
NSLog(@"This is device token%@", deviceToken);
//NSString *deviceTokenString = [deviceToken description];
[FIRMessaging messaging].APNSToken = deviceToken;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
[[UIApplication sharedApplication] registerForRemoteNotifications];
RCTAppSetupPrepareApp(application);
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
//...OTHER CODE HERE
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// ...
}];
[[FIRMessaging messaging] setDelegate:self];
return YES;
}
FirebaseMessaging.instance.requestPermission().then((value) {
FirebaseMessaging.instance.getToken().then((value) {
print('TOken$value');
});
});
onRegister(token) {
if (Platform.OS === 'ios') {
messaging().setAPNSToken(token.token);
}
}