Firebase推送通知无法在后台IOS中接收

时间:2018-09-06 07:34:40

标签: ios firebase react-native push-notification

我是Firebase的新手,我可以在前台收到通知,但在后台什么都没收到。仅当“我的应用”再次进入前台时,通知才会显示。

  

我已经启用功能>后台模式>后台获取,从Xcode进行远程通知。

     

使用Advanced Rest Client发送请求并已将“优先级”设置为高,将“ content_available”设置为true

{
  "to":"/topics/NFNKJABFLANKSL_ASKDWS",
  "content_available":true,
  "priority":"high",
  "notification":{ 
    "title":"234",
    "body":"234", 
    "additionalData":"xxx", 
    "sound":"default", 
    "priority":"high", 
    "content_available":"true" 
 }, 
 "data":{ 
   "title":"123", 
   "body":"123", 
   "additionalData":"xxx", 
   "sound":"default", 
   "priority":"high", 
   "content_available":"true" 
 }
}

我已经按照Docs中的步骤进行操作,但是仍然无法解决此问题。

请帮助。

  • “ react-native-firebase”:“ ^ 4.3.8”
  • “ react-native-push-notification”:“ ^ 3.1.1”
  • pod'Firebase / Core'
  • pod'Firebase / Messaging','〜> 5.3.0'
  • pod'Firebase / Functions','〜> 5.3.0'
  • pod'FirebaseInstanceID'

这是我的AppDelegate.m:

#import "AppDelegate.h"
#import <Firebase.h>
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"
#import <UserNotifications/UserNotifications.h>
#import <React/RCTPushNotificationManager.h>


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


@implementation AppDelegate

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

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // [START configure_firebase]
  [FIRApp configure];
  // [END configure_firebase]

  [RNFirebaseNotifications configure];

  //  added
  [FIRMessaging messaging].shouldEstablishDirectChannel = YES;

  // [START set_messaging_delegate]
  [FIRMessaging messaging].delegate = self;
  // [END set_messaging_delegate]

  // Register for remote notifications. This shows a permission dialog on first run, to
  // show the dialog at a more appropriate time move this registration accordingly.
  // [START register_for_notifications]
  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];
  // [END register_for_notifications]


  NSURL *jsCodeLocation;

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"MyApp"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  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];

  [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self]; //Add This Line
  return YES;
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  // 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];

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

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

- (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];

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

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

  completionHandler(UIBackgroundFetchResultNewData);
}
@end

这是我的Index.js代码:

  initPushNotification() {
      console.log('init')
      PushNotification.configure({

          // (optional) Called when Token is generated (iOS and Android)
          onRegister: function (token) {
              AppStore.setFCMToken(token.token)
              FirebaseService.setTokenData(token.token)
          },

          // (required) Called when a remote or local notification is opened or received
          onNotification: function (notification) {
              if (!notification.userInteraction) {
                  PushNotification.setApplicationIconBadgeNumber(0);
              }
              if (notification) {
                  console.log(notification)
                  PushNotification.localNotification({
                      /* Android Only Properties */
                      id: '0', // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
                      ticker: "My Notification Ticker", // (optional)
                      autoCancel: true, // (optional) default: true
                      largeIcon: "ic_launcher", // (optional) default: "ic_launcher"
                      smallIcon: "ic_notification", // (optional) default: "ic_notification" with fallback for "ic_launcher"
                      bigText: "My big text that will be shown when notification is expanded", // (optional) default: "message" prop
                      subText: "This is a subText", // (optional) default: none
                      color: "red", // (optional) default: system default
                      vibrate: true, // (optional) default: true
                      vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
                      tag: 'some_tag', // (optional) add tag to message
                      group: "group", // (optional) add group to message
                      ongoing: false, // (optional) set whether this is an "ongoing" notification

                      /* iOS only properties */

                      message: "My Notification Message", // (required)
                      playSound: false, // (optional) default: true
                      soundName: 'default', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
                      number: '10', // (optional) Valid 32 bit integer specified as string. default: none (Cannot be zero)
                      repeatType: 'day', // (Android only) Repeating interval. Could be one of `week`, `day`, `hour`, `minute, `time`. If specified as time, it should be accompanied by one more parameter 'repeatTime` which should the number of milliseconds between each interval
                      actions: '["Yes", "No"]',  // (Android only) See the doc for notification actions to know more
                  });
              }
              // process the notification

              // required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
              // notification.finish(PushNotificationIOS.FetchResult.NoData);
          },

          // ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
          senderID: "XXXXXXXXXX1", // my sender ID

          // IOS ONLY (optional): default: all - Permissions to register.
          permissions: {
              alert: true,
              badge: true,
              sound: true
          },

          // Should the initial notification be popped automatically
          // default: true
          popInitialNotification: true,

          /**
            * (optional) default: true
            * - Specified if permissions (ios) and token (android and ios) will requested or not,
            * - if not, you must call PushNotificationsHandler.requestPermissions() later
            */
          requestPermissions: true,
      });
  }

  getTokenAndMessage(){
    firebase.messaging().getToken()
      .then(fcmToken => {
        if (fcmToken) {
          this.setState({ deviceToken: fcmToken})
          // user has a device token
          this.onTokenRefreshListener = firebase.messaging().onTokenRefresh(fcmToken => {
               // Process your token as required
           })
        } else {
          // user doesn't have a device token yet
        }
      });
      this.messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
          // Process your message as required
        this.setState({ data: message.data})
        console.log("Log ",(this.state.data))
        PushNotification.localNotification({
          title: this.state.data.title,
          message: this.state.data.body
        })
      });
      firebase.messaging().subscribeToTopic('/topics/NFNKJABFLANKSL_ASKDWS');
  }

  getNotification(){
    this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => {
        // Process your notification as required
        // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
    });
    this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
        // Process your notification as required
    });
    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
        // Get the action triggered by the notification being opened
        const action = notificationOpen.action;
        // Get information about the notification that was opened
        const notification: Notification = notificationOpen.notification;
    });
    firebase.notifications().getInitialNotification()
      .then((notificationOpen: NotificationOpen) => {
        if (notificationOpen) {
          // App was opened by a notification
          // Get the action triggered by the notification being opened
          const action = notificationOpen.action;
          // Get information about the notification that was opened
          const notification: Notification = notificationOpen.notification;
        }
      });
  }
  componentDidMount (){
      this.initPushNotification()
      firebase.messaging().hasPermission()
        .then(enabled => {
          if (enabled) {
            // user has permissions
            console.log('user has permissions')
            this.getTokenAndMessage();
            this.getNotification();
          } else {
            // user doesn't have permission
            firebase.messaging().requestPermission()
              .then(() => {
                // User has authorised
                console.log('user has authorised')
                this.getTokenAndMessage();
                this.getNotification();
              })
              .catch(error => {
                // User has rejected permissions
                console.log('user has rejected permissions')
              });
          }
        });
      }
componentWillUnmount() {
      this.messageListener();
      this.notificationDisplayedListener();
      this.notificationListener();
      this.notificationOpenedListener();
  }

0 个答案:

没有答案