didReceiveLocalNotification, didReceiveRemoteNotification и willPresentNotification никогда не срабатывает, когда появляются уведомления, React Native App - PullRequest
0 голосов
/ 22 сентября 2019

Я пытаюсь реализовать уведомления в приложении, работающем на натуре, на iOS, и столкнулся со странной проблемой.Приложение может отображать локальные уведомления и удаленные уведомления, поступающие из firebase, но оно не вызывает событие «onNotification» реакции-нативного-push-уведомления, как ожидалось.Я прошел через многие форумы в поисках решения, но я до сих пор не нашел его, поэтому я прошу вашей помощи.

После исследования я понял, что функции target-c "didReceiveLocalNotification" и "didReceiveRemoteNotification""никогда не запускаются, поэтому я предположил, что это причина, по которой" onNotification "тоже не срабатывает.К сожалению, я абсолютный новичок в этом языке, поэтому не могу понять причину проблемы.

Глядя на документацию "didReceiveLocalNotification", я прочитал, что эта функция устарела и что я должен использовать "willPresentNotification "вместо этого, но, как и другие, он никогда не запускается.

Для справки, я следовал этому руководству по обработке уведомлений в iOS: https://firebase.google.com/docs/cloud-messaging/ios/client. Я тестирую на iOS 13, реагирую наСобственный 0.60.5, push-notifiaction-ios ^ 1.0.2, response-native-push-Уведомление ^ 3.1.3 и response-native-firebase ^ 5.5.6.

AppDelegate.m


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
    [FIRMessaging messaging].delegate = self;
  }
  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];

  // Load RootView ...

  return YES;
}
// sourceURLForBridge function ...

// Required to register for notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
  [RNCPushNotificationIOS didRegisterUserNotificationSettings:notificationSettings];
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  // Never called
  [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
  // Never called
  [RNCPushNotificationIOS didReceiveLocalNotification:notification];
}

//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  // Never called
  completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
  //completionHandler(UNNotificationPresentationOptionAlert);
}

PushNotification и конфигурация firebase


function configurePushNotification(){
  PushNotification.configure({
    onRegister: function(token) {
      console.warn("TOKEN:", token);
    },
    onNotification: function(notification) {
      console.warn("NOTIFICATION:", notification);

      // Never called

      notification.finish(PushNotificationIOS.FetchResult.NoData);
    },
    permissions: {
      alert: true,
      badge: true,
      sound: true
    },
    popInitialNotification: true,
    requestPermissions: true
  });
}
async function checkPermission(onReady) {
  const enabled = await firebase.messaging().hasPermission();
  if (enabled) {
    console.warn('checkPermission enabled');
    getToken(onReady);
  } else {
    console.warn('checkPermission disabled');
    requestPermission(onReady);
  }
}

async function requestPermission(onReady) {
  try {
    await firebase.messaging().requestPermission();
        // User has authorised
        console.warn('requestPermission try');
        getToken(onReady);
  } catch (error) {
        // User has rejected permissions
        console.error(error)
        console.warn('requestPermission rejected');
    }
}

async function getToken(onReady) {
  fcmToken = await AsyncStorage.getItem('fcmToken');
  if (!fcmToken) {
    fcmToken = await firebase.messaging().getToken();
    if (fcmToken) {
          // user has a device token
          await AsyncStorage.setItem('fcmToken', fcmToken);
      }
  }
  console.warn(fcmToken)
  if(onReady) onReady()
}

class App extends React.Component {

  async componentDidMount() {
    checkPermission()
    configurePushNotification()
  }

  render(){
    return (
      // View ...
    )
  }
};

Спасибо за вашу помощь!

EDIT : После расследования я понял, что эти события перестают работать после того, как ядобавил Firebase / Messaging в мой подфайл.Но согласно документации Firebase, это не нормальное поведение.Любая идея о причине этого?

...