Push-уведомления не отправляются с проверкой, несмотря на наличие APN и токена FCM конкретного устройства

avatar
J Robz
1 июля 2021 в 17:59
293
0
0

Я просмотрел coderhelper и Google в поисках ответа на этот вопрос, вот некоторые из вещей, которые я пробовал:

  • Следуя инструкциям Клиента Google и Получите руководства.
  • Убедитесь, что firebase имеет правильные настройки APN.
  • Этот ответ coderhelper.
  • Этот ответ coderhelper.

Я просмотрю то, что у меня есть:

AppDelegate.m:

#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

@import Firebase;
@import UserNotifications;

/** Flipper **/
#ifdef FB_SONARKIT_ENABLED
  #import <FlipperKit/FlipperClient.h>
  #import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
  #import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
  #import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
  #import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
  #import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>

  static void InitializeFlipper(UIApplication *application) {
    FlipperClient *client = [FlipperClient sharedClient];
    SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
    [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
    [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
    [client addPlugin:[FlipperKitReactPlugin new]];
    [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
    [client start];
  }
#endif
/** End Flipper **/

// Implement UNUserNotificationCenterDelegate to receive display notification via APNS for devices
// running iOS 10 and above.
@interface AppDelegate () <UNUserNotificationCenterDelegate>
@end

@implementation AppDelegate

NSString *const kGCMMessageIDKey = @"gcm.message_id";

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  #ifdef FB_SONARKIT_ENABLED
    InitializeFlipper(application);
  #endif

  [FIRApp configure];

  [FIRMessaging messaging].delegate = self;

  /* Messaging */
  if ([UNUserNotificationCenter class] != nil) {
    // iOS 10 or later
    // For iOS 10 display notification (sent via APNS)
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
        UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
    [[UNUserNotificationCenter currentNotificationCenter]
        requestAuthorizationWithOptions:authOptions
        completionHandler:^(BOOL granted, NSError * _Nullable error) {
          // ...
        }];
  } else {
    // iOS 10 notifications aren't available; fall back to iOS 8-9 notifications.
    UIUserNotificationType allNotificationTypes =
    (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings =
    [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
    [application registerUserNotificationSettings:settings];
  }

  [application registerForRemoteNotifications];

  /*
  [[FIRMessaging messaging] tokenWithCompletion:^(NSString *token, NSError *error) {
    if (error != nil) {
      NSLog(@"Error getting FCM registration token: %@", error);
    } else {
      NSLog(@"FCM registration token: %@", token);
      //[FIRMessaging messaging].fcmRegTokenMessage.text = token;
    }
  }];
  /* End Messaging */

  /* Bridge */
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"UBFounders"
                                            initialProperties:nil];

  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  /* End Bridge */

  return YES;
}

/* Monitor token refresh */
- (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];
    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
}
/* End token refresh */

// [START receive_message]
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // [START_EXCLUDE]
  // Print message ID.
  if (userInfo[kGCMMessageIDKey]) {
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  }
  // [END_EXCLUDE]

  // Print full message.
  NSLog(@"%@", userInfo);

  completionHandler(UIBackgroundFetchResultNewData);
}
// [END receive_message]

// [START ios_10_message_handling]
// Receive displayed notifications for iOS 10 devices.
// Handle incoming notification messages while app is in the foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  NSDictionary *userInfo = notification.request.content.userInfo;

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // [START_EXCLUDE]
  // Print message ID.
  if (userInfo[kGCMMessageIDKey]) {
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  }
  // [END_EXCLUDE]

  // Print full message.
  NSLog(@"%@", userInfo);

  // Change this to your preferred presentation option
  completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert);
}

// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void(^)(void))completionHandler {
  NSDictionary *userInfo = response.notification.request.content.userInfo;
  if (userInfo[kGCMMessageIDKey]) {
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  }

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // Print full message.
  NSLog(@"%@", userInfo);

  completionHandler();
}
// [END ios_10_message_handling]

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
  #if DEBUG
    return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
  #else
    return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
  #endif
}

@end

По сути, я запускаю приложение, получаю регистрационный токен FCM из консоли следующим образом: enter image description here

Затем я добавляю токен в Центр уведомлений и пробую тестовую отправку следующим образом: enter image description here

Из отчетов видно, что ни одно из уведомлений не получено, а именно: enter image description here

Не знаю, что еще попробовать. Мысли?


РЕДАКТИРОВАТЬ: обновить, чтобы отразить соответствующий javascript:

index.js

import messaging, { firebase } from '@react-native-firebase/messaging';

messaging().setBackgroundMessageHandler(async remoteMessage => {});

App.js

import messaging from "@react-native-firebase/messaging";

// Push notifications function
async function push_notifications_setup() {
  const authStatus = await messaging().requestPermission();
  // Check if we have permissions
  if (authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL) {
    messaging().subscribeToTopic("podcasts");
  }
}

export default function App() {
  // TODO: Uncomment for push notifications 
  // Request push notification permissions
  push_notifications_setup();

  ...
}

Источник
Francesco Clementi
1 июля 2021 в 20:16
0

Какой пакет вы используете? реагировать-нативное-push-уведомление или реагировать-нативное-firebase? Вы реализовали код javascript? Без него не получится

J Robz
1 июля 2021 в 21:01
0

@FrancescoClementi Я добавил JS, но не думаю, что это актуально при использовании консоли firebase.

El Tomato
2 июля 2021 в 01:02
0

У вас отсутствует один или несколько методов делегата. Где didRegisterForRemoteNotificationsWithDeviceToken?

Francesco Clementi
2 июля 2021 в 06:32
0

Кроме того, где вы берете токен? Я не мог получить уведомление, когда получал токен с помощью push-уведомления, который не был токеном FCM.

J Robz
2 июля 2021 в 14:45
0

@ElTomato Я не нашел ни одного метода делегата с таким именем ни в одном учебнике, который я нашел, какой код я должен вставить? @FrancescoClementi Я получаю токен FCM с консоли. Он выводится из метода didReceiveRegistrationToken.

J Robz
2 июля 2021 в 18:03
0

Хорошо @FrancescoClementi и @ElTomato Кажется, я что-то понял. Я заставил его работать, добавив этот код в AppDelegate.m, но с раскомментированной строкой 179. Но что это за накрутка и что мне нужно сделать, чтобы это заработало на продакшене?

Ответы (0)