【问题标题】:Not receiving notification when app in background (iOS react-native)当应用程序在后台时没有收到通知(iOS react-native)
【发布时间】:2019-07-05 14:27:56
【问题描述】:

我正在为我的一个项目实施 react-native-firebase 并尝试在其中添加通知功能。但我在获取通知时遇到问题。当我使用 firebase api“https://fcm.googleapis.com/fcm/send”发送通知时,我会在应用程序处于前台时收到通知。但是当应用程序在后台并发送通知时,我没有收到任何通知。但只要我打开应用程序,我就会收到通知。

我已经复制了 googleservice-info.plist 文件并在 firebase 中上传了 auth 密钥。

我的主要js代码:


        messagaing.hasPermission()
            .then((enabled) => {
                if (enabled) {
                    messagaing.getToken()
                        .then(async token => {
                            const deviceId = await AsyncStorage.getItem('deviceId');
                            if (!deviceId) {
                                this.registerTokenOnServer(token)
                            } else {
                                this.setState({
                                    deviceId
                                })
                            }
                            console.log('fcm token', token)
                        })
                        .catch(error => { console.log('fcm error', error) })
                } else {
                    messagaing.requestPermission()
                        .then(() => { console.log('fcm token') })
                        .catch(() => { console.log('fcm error') })
                }
            })
            .catch(error => {
                console.log('fcm error', error)
            })

        messagaing.onMessage((message) => {
            console.log('fcm noti on message data', message)

            let notification_to_be_displayed = new firebase.notifications.Notification({
                sound: 'default',
                show_in_foreground: true,
                title: message._data.title,
                body: message._data.message,
            });
            firebase.notifications().displayNotification(notification_to_be_displayed);

            firebase.notifications().onNotificationOpened((notificationOpen) => {
                const notification = notificationOpen.notification;
                console.log('fcm open ', notification)
                if (notification.data.obj_type == '1') {
                    this.props.navigation.navigate('ProductDetailPage', { prodId: notification.data.obj_id, })
                } else {
                    this.props.navigation.navigate('SubCategoryPage', { catId: notification.data.obj_id, catName: 'Categories' })
                }
            })
        });

我的 AppDelegate.h :

#import <UserNotifications/UserNotifications.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate>

@property (nonatomic, strong) UIWindow *window;

@end

我的 AppDelegate.m :

#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#if __has_include(<React/RNSentry.h>)
#import <React/RNSentry.h> // This is used for versions of react >= 0.40
#else
#import "RNSentry.h" // This is used for versions of react < 0.40
#endif
#import "RNGoogleSignin.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <Firebase.h>
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"reactenduser"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];

  [RNSentry installWithRootView:rootView];

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

  // define UNUserNotificationCenter
  [FIRApp configure];
  [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
  [RNFirebaseNotifications configure];

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

  [[FBSDKApplicationDelegate sharedInstance] application:application
                           didFinishLaunchingWithOptions:launchOptions];

  return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

  return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                        openURL:url
                                              sourceApplication:sourceApplication
                                                     annotation:annotation
          ]
  || [RNGoogleSignin application:application
                         openURL:url
               sourceApplication:sourceApplication
                      annotation:annotation
      ];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
  [FBSDKAppEvents activateApp];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
  [[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
  [[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
  [[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}

-(void) userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {

  [[RNFirebaseMessaging instance] didReceiveRemoteNotification:response.notification.request.content.userInfo];
  completionHandler();
}

@end

当我的应用程序进入后台时发送通知时,我没有收到任何数据或错误。只有当它进入前台时,我才能看到日志。

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 你在原生ios项目中开启后台通知了吗?

标签: ios react-native


【解决方案1】:

您需要为远程消息打开后台功能。

检查图像

请注意,在我的项目中,我有后台提取,我想你可以跳过它。

【讨论】:

  • 您好,感谢您的快速回复。对不起,我忘了提,但我已经做到了。还有什么我可能遗漏的吗?
  • 我刚刚检查了这个medium.com/@anum.amin/…,我不确定你是否拥有this.checkPermission(); this.createNotificationListeners();
  • 也试过了,后台还是没有通知或者关闭了。无法理解这里的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
相关资源
最近更新 更多