Привет Я реализую FCM (Fire base cloud messaging). Я сделал приложение для получения уведомлений и данных с консоли FCM. У меня есть уведомление о моем сервере и уведомление о пожарной базе. Я хочу обрабатывать 2 типа уведомления (с моего сервера и из FCM) отдельно. Я прошел через документы, и это может быть достигнуть путем swizzling обработчика уведомлений в AppDelegateМетод обмена сообщениями Firebase swizzling не работает
Но проблема в том, что я могу получить только данные сообщения ТСМ (IOS 10) в
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {}
и
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {}
обратного вызова для FCM делегата
// The callback to handle data message received via FCM for devices running iOS 10 or above.
- (void)applicationReceivedRemoteMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage {
// Print full message
NSLog(@"Can get here firebase?%@", [remoteMessage appData]);
}
выше обратного вызова никогда не ча lled
Как мы можем использовать swizzling для отправки сообщения обработчика FCM отдельно?
Вот мой AppDelegate вариант didfinishlaunchingwith
application.applicationIconBadgeNumber = 0;
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
}
];
// For iOS 10 display notification (sent via APNS)
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
// For iOS 10 data message (sent via FCM)
[[FIRMessaging messaging] setRemoteMessageDelegate:self];
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
// [START configure_firebase]
[FIRApp configure];
// [END configure_firebase]
// Add observer for InstanceID token refresh callback.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
_rootViewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
[self.window setRootViewController:_rootViewController];
[self.window makeKeyAndVisible];
NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (remoteNotification)
[self handleRemoteNotification:remoteNotification shouldPrompt:NO];
self.isFirstTime = true;
self.isJustForRefresh = 0;
return YES;
Кто знает, как заставить его работать?
Edit: вот мой наблюдатель функции наблюдения и функции didregisterRemoteNotification
// [START refresh_token]
- (void)tokenRefreshNotification:(NSNotification *)notification {
// Note that this callback will be fired everytime a new token is generated, including the first
// time. So if you need to retrieve the token as soon as it is available this is where that
// should be done.
NSString *refreshedToken = [[FIRInstanceID instanceID] token];
NSLog(@"InstanceID token: %@", refreshedToken);
// Connect to FCM since connection may have failed when attempted before having a token.
[self connectToFcm];
// TODO: If necessary send token to application server.
}
// [END refresh_token]
// [START connect_to_fcm]
- (void)connectToFcm {
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(@"Unable to connect to FCM. %@", error);
} else {
NSLog(@"Connected to FCM.");
}
}];
}
// [END connect_to_fcm]
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
NSString *sanitizedDeviceToken = [[[[deviceToken description]
stringByReplacingOccurrencesOfString:@"<" withString:@""]
stringByReplacingOccurrencesOfString:@">" withString:@""]
stringByReplacingOccurrencesOfString:@" " withString:@""];
DLog(@"sanitized device token: %@", sanitizedDeviceToken);
[PushNotificationManager API_registerAPNSToken:sanitizedDeviceToken
onCompletion:^(BOOL success, NSError *error){}];
[[FIRInstanceID instanceID]setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
}
Обновлено: У меня есть включить эту функцию, но до сих пор не работает
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
if (userInfo[@"gcm.message_id"] != nil) {
NSLog(@"Should get here FCM?");
[[FIRMessaging messaging]appDidReceiveMessage:userInfo];
}else {
NSLog(@"test fetchCompletion handler: %@",userInfo.description);
}
}
нибудь есть идеал? –
Вы не должны использовать swizzling https://github.com/onmyway133/blog/issues/64 – onmyway133