【问题标题】:React-native not receiving push notifications, using Firebase Cloud functionsReact-native 不接收推送通知,使用 Firebase Cloud 功能
【发布时间】:2018-02-15 04:49:07
【问题描述】:

注意:我是在真机上测试

我正在尝试使用 Firebase Cloud Functions 向我的 react-native 应用发送推送通知。

下面是我的云函数:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.sendNewMessageNotification = functions.database.ref('users').onWrite(event => {
    const getValuePromise = admin.database()
                                 .ref('users')
                                 .orderByKey()
                                 .limitToLast(1)
                                 .once('value');

    return getValuePromise.then(snapshot => {

        const payload = {
            notification: {
                title: 'Dot notification',
                body: 'A new user has been added',
            }
        };

        return admin.messaging()
                    .sendToTopic('secret-chatroom', payload);
    });
});

上面的云函数正在执行,没有任何错误:

下面是我应用中的通知监听器:

import * as Type from '../actions/types';
import FCM, { FCMEvent,
              NotificationType,
              WillPresentNotificationResult,
              RemoteNotificationResult } from 'react-native-fcm';
import { Platform } from 'react-native';
import { takeLatest, put, call } from 'redux-saga/effects';


function* listenToNotifications() {
    FCM.requestPermissions();
    FCM.getFCMToken()
       .then(token => {
           console.log(token) //being logged
       });
    FCM.subscribeToTopic('secret-chatroom');

    FCM.on(FCMEvent.Notification, async (notif) => {
        console.log(notif); //not being logged
        alert('Notification recieved');

        if (Platform.OS === 'ios') {
            switch (notif._notificationType) {
                case NotificationType.Remote:
                    notif.finish(RemoteNotificationResult.NewData); //other types available: RemoteNotificationResult.NewData, RemoteNotificationResult.ResultFailed
                    break;
                case NotificationType.NotificationResponse:
                    notif.finish();
                    break;
                case NotificationType.WillPresent:
                    notif.finish(WillPresentNotificationResult.All); //other types available: WillPresentNotificationResult.None
                    break;
              }
            }
    });

    FCM.on(FCMEvent.RefreshToken, token => {
        console.log(token);
    });
}


export default function* appNotificationsSaga() {
    yield takeLatest(Type.LISTEN_TO_NOTIFICATIONS, listenToNotifications);
}

正在记录 FCM.getFCMToken 值,但在执行云功能时我没有收到任何通知。有人可以告诉我我做错了什么吗?

【问题讨论】:

    标签: firebase react-native redux firebase-cloud-messaging redux-saga


    【解决方案1】:

    首先,您不会在模拟器上收到通知,因此请确保您已调试具有互联网连接的远程设备。

    其次,按照react-native-fcm的细节,有两种做法

    Pod 方法:

    确保您的 Cocoapods 版本 > 1.0

    配置项目:

    cd ios && pod init
    

    (如果出现语法错误,请打开 YOURApp.xcodeproj/project.pbxproj 并修复它们。)

    编辑新建的Podfile,可以在ios文件夹->Podfile中找到 将 + 行添加到文件中

    # Pods for YOURAPP
    + pod 'Firebase/Messaging'
    target 'YOURApp' do
    + pod 'react-native-fcm', :path => '../node_modules/react-native-fcm'
    ...
    end
    

    安装 Firebase/Messaging pod:

    pod install
    

    如果这种方法不起作用,您可以按照

    非 Cocoapod 方法

    1. 从 Integrate without CocoaPods 下载 Firebase SDK 框架。 导入库、添加功能(后台运行和推送通知)、上传 APNS 等等等...
    2. 将框架放在 ios/Frameworks 文件夹下
    3. 按照自述文件链接框架(分析+消息传递)

    共享步骤(这应该适用于两种方法)

    编辑 AppDelegate.h:

    + @import UserNotifications;
    +
    + @interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
    - @interface AppDelegate : UIResponder <UIApplicationDelegate>
    Edit AppDelegate.m:
    
    + #import "RNFIRMessaging.h"
      //...
    
      - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
      {
      //...
    +   [FIRApp configure];
    +   [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
    
        return YES;
     }
    
    +
    + - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
    + {
    +   [RNFIRMessaging willPresentNotification:notification withCompletionHandler:completionHandler];
    + }
    +
    + #if defined(__IPHONE_11_0)
    + - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
    + {
    +   [RNFIRMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
    + }
    + #else
    + - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler
    + {
    +   [RNFIRMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
    + }
    + #endif
    +
    + //You can skip this method if you don't want to use local notification
    + -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    +   [RNFIRMessaging didReceiveLocalNotification:notification];
    + }
    +
    + - (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
    +   [RNFIRMessaging didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
    + }
    

    添加功能 现在,当您想在 Xcode 中构建您的应用程序时,请确保在您的 capabilities 设置中打开推送通知并将其与您的苹果开发者帐户集成。 然后尝试在您的设备上运行该应用程序,它应该可以正常运行。

    Select your project Capabilities and enable:
    Push Notifications
    Background Modes > Remote notifications.
    

    这应该使推送通知起作用,它的步骤很长,但它只完成了一次 :)

    【讨论】:

    • 我已经完成了所有这些步骤,我正在真实设备上进行测试
    • 你采用了哪种方法?
    • 您是否在 ios 路径中添加了 GoogleService-Info.info,是否手动将库链接到您的项目(从 /{YOUR_APP_PATH}/node_modules/react-native-fcm/ios 添加 RNFIRMessaging.xcodeproj在您的项目文件中并在二进制文件中添加 .a 文件)然后尝试清理您的项目并构建它。
    • 您需要手动添加 GoogleService-Info.info(我只知道如何在 XCode 中执行此操作):右键单击您的项目 单击“将文件添加到 '项目名称'” 选择 GoogleService- Info.plist 文件 点击确定
    • 非常感谢..不知道firebase不会响应模拟器,所以我浪费了一些时间试图在最简单的功能中找到问题..现在一切正常..谢谢又来了!
    【解决方案2】:

    您没有收到通知可能是因为 firebase 未正确集成到您的应用程序中。正确集成的步骤如下:

    react-native-firebase 库对我不起作用。使用 react-native-fcm 集成 firebase 以响应本机应用程序成功接收推送通知。

    1.安装 react-native-fcm: npm install react-native-fcm --save

    1. 从 Firebase 控制台, 对于 Android:下载 google-services.json 文件并将其放在 android/app 目录中。 对于 iOS:下载 GoogleService-Info.plist 文件并将其放在 /ios/your-project-name 目录中(Info.plist 旁边)

    3.配置项目使用: cd ios && pod init

    4.编辑新创建的 Podfile: 吊舱安装

    5.编辑AppDelegate.h:

        @import UserNotifications;
    
        @interface AppDelegate:UIResponder<UIApplicationDelegate,UNUserNotificationCenterDelegate>
    
        @interface AppDelegate : UIResponder <UIApplicationDelegate>
    

    6.编辑AppDelegate.m:

    #import "RNFIRMessaging.h"
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    

    {

    [FIRApp configure];
    [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
    
    return YES;
    

    }

    -(void)userNotificationCenter:(UNUserNotificationCenter *)center 
    willPresentNotification:(UNNotification *)notification 
    withCompletionHandler:(void (^) . 
          (UNNotificationPresentationOptions))completionHandler
     {
        [RNFIRMessaging willPresentNotification:notification 
         withCompletionHandler:completionHandler];
     }
    
    #if defined(__IPHONE_11_0)
    
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center 
      didReceiveNotificationResponse:(UNNotificationResponse *)response 
       withCompletionHandler:(void (^)(void))completionHandler
    {
        [RNFIRMessaging didReceiveNotificationResponse:response 
         withCompletionHandler:completionHandler];
    }
    
    #else
    
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center 
      didReceiveNotificationResponse:(UNNotificationResponse *)response 
      withCompletionHandler:(void(^)())completionHandler
    {
        [RNFIRMessaging didReceiveNotificationResponse:response 
        withCompletionHandler:completionHandler];
     }
    
    #endif
    
     //You can skip this method if you don't want to use local notification
    -(void)application:(UIApplication *)application 
    didReceiveLocalNotification:(UILocalNotification *)notification {
    
    [RNFIRMessaging didReceiveLocalNotification:notification];
    
     }
    
    - (void)application:(UIApplication *)application 
    didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo 
    fetchCompletionHandler:(nonnull void (^) . 
    (UIBackgroundFetchResult))completionHandler{
    
    [RNFIRMessaging didReceiveRemoteNotification:userInfo 
    fetchCompletionHandler:completionHandler];
    }
    

    7.XCode中添加头文件路径:

    打开 XCode。 按 CMD+1 或单击 XCode 项目。 转到构建设置,选择全部和组合。 在 searchg 选项卡中搜索标题搜索路径。 确保有一行 $(SRCROOT)/../node_modules/react-native-fcm/ios。如果没有,请添加它。

    8.添加GoogleService-Info.plist:

    确保文件不只是移动到文件夹中。您需要右键单击 XCode 中的项目文件夹并将文件添加到 .选择文件时,在“选项”页面中根据需要选择“复制”。

    9.共享库设置:

    如果您使用 Pod 安装方法,请确保在 Library 文件夹下看到 Pods.xcodeproj。 确保您在 Library 文件夹下看到 RNFIRMessaging.xcodeproj。 如果您没有看到任何这些文件,请通过右键单击库文件夹并添加文件来添加它们以将它们添加回来。 Pods.xcodeproj 应该在 ios/Pods/ 下,RNFIRMessaging.xcodeproj 应该在 node_modules/react-native-fcm/ios 下。 确保在 Build Phases 选项卡下的 Link Binary With Libraries 下看到 libRNFIRMessaging.a。如果没有,请将Library文件夹下的RNFIRMessaging.xcodeproj下的文件拖到那里。

    10.添加功能 选择您的项目功能并启用: 推送通知 后台模式 > 远程通知。

    FirebaseAppDelegateProxyEnabled 此说明假定您有 FirebaseAppDelegateProxyEnabled=YES(默认),以便 Firebase 将挂钩推送通知注册事件。如果您关闭此标志,您将自行管理 APNS 令牌并与 Firebase 令牌链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 2019-12-18
      • 1970-01-01
      • 2021-06-28
      相关资源
      最近更新 更多