React native - Push Notification (Firebase)

How to add Push Notification in your project? I use firebase to send cloud messages by Push Notification. First of all, you click the website "https://rnfirebase.io/" , and click the menu "Cloud Messaging"

Installation

# Install & set up the app module
yarn add @react-native-firebase/app

# Install the messaging module
yarn add @react-native-firebase/messaging

# If you're developing your app using iOS, run this command
cd ios/ && pod install

iOS Setup

AppDelegate.m

@import Firebase;

@interface AppDelegate () <FIRMessagingDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [FIRApp configure];
    [application registerForRemoteNotifications];
    [FIRMessaging messaging].delegate = self;
}

- (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.
}


- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  NSLog(@"error: %@", error);
}

Android Setup

/appName/android/app/src/main/AndroidManifest.xml

<service android:name=".MyFirebaseMessagingService" android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

/android/app/src/main/java/com/appName/MyFirebaseMessagingService.java

package com.stylepedia;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import android.util.Log;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private final String TAG = "FCMDemo";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        // TODO(developer): Handle FCM messages here.
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if the message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }

    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }

    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "From: " + token);
        sendRegistrationToServer(token);
    }
}

React Native

You can get token by this function, if the device didn't open Push Notification, you won't get the token, so you make sure that the user have opened the notifications.

import messaging from '@react-native-firebase/messaging'

if (!messaging().isDeviceRegisteredForRemoteMessages) {
    messaging().registerDeviceForRemoteMessages()
}
messaging().getToken()
.then(fcmToken => {
  if (fcmToken) {
    console.warn(fcmToken)
    if (Platform.OS === 'ios') {
      this.iosTokenNetWork(fcmToken)
    }
    else {
      this.androidTokenNetWork(fcmToken)
    }
  } else {
    console.warn('user doesn t have a device token yet')
    // user doesn't have a device token yet
  }
})

You can use this function to check if the user opens the push notification switch on the user's device.

messaging().requestPermission().then((response: any) => {
  //
}

// if user click allow app push notification on pop-up,I can get token by function: 

messaging().requestPermission().then((response: any) => {
    if (!messaging().isDeviceRegisteredForRemoteMessages) {
        messaging().registerDeviceForRemoteMessages()
      }
      messaging().getToken()
        .then(fcmToken => {
          if (fcmToken) {
            if (Platform.OS === 'ios') {
              this.iosTokenNetWork(fcmToken)
            }
            else {
              this.androidTokenNetWork(fcmToken)
            }
          } else {
            console.warn('user doesn t have a device token yet')
            // user doesn't have a device token yet
          }
        })
})

You can click Push notification and go to another page when the App is in the background.

messaging().setBackgroundMessageHandler(async remoteMessage => {
        if (remoteMessage) {
          appsFlyer.trackEvent("Open_notification")
          analytics().logEvent('Open_notification', {
            value: '',
          });
          if (remoteMessage.data.send_user_history_id) {
            this.pushRequest(remoteMessage.data.send_user_history_id)
          }
          if (remoteMessage.data.url === "MixMatch") {  
              this.props.navigation.push('MyClosetDetailPage', {
                product_id: remoteMessage.data.push_id,
                returnPage: 'Tabs',
              })
  
          }
          if (remoteMessage.data.url === "StreetSnap") {
            this.timer = setTimeout(() => {
              this.props.navigation.navigate('PushlookbookStreetSnapPage', {
                streetId: remoteMessage.data.push_id,
                returnPage: 'Tabs',
              })
            }, 500);
          }
      }
});

You can click Push notification and go to another page when the App is closed

messaging()
      .getInitialNotification()
      .then(remoteMessage => {
        if (remoteMessage) {
          appsFlyer.trackEvent("Open_notification")
          analytics().logEvent('Open_notification', {
            value: '',
          });
          // alert(JSON.stringify(remoteMessage) )

            if (remoteMessage.data.url === "MixMatch") {

              this.timer = setTimeout(() => {
                this.props.navigation.push('MyClosetDetailPage', {
                  product_id: remoteMessage.data.push_id,
                  returnPage: 'Tabs',
                })
              }, 500);
            }
            if (remoteMessage.data.url === "StreetSnap") {
              this.timer = setTimeout(() => {
                this.props.navigation.navigate('PushlookbookStreetSnapPage', {
                  streetId: remoteMessage.data.push_id,
                  returnPage: 'Tabs',
                })
              }, 500);
            }
          }
})

Create Notification Service Extension

If I want to send an iOS Push Notification with picture to my iPhone, I have to add the iOS Push Notification with Notification Service Extension.

  1. In the Xcode menu, go to File > New > Target.
  2. Select the Notification Service Extension.
  3. Gives the name the Extension service and click the finish button.

and enable Push Notification and App Group capabilities in iOS App target.

NotificationService.h

#import <UserNotifications/UserNotifications.h>

@interface NotificationService : UNNotificationServiceExtension

@end

NotificationService.m

#import "NotificationService.h"
@import Firebase;

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    // Modify the notification content here...
  if (self.bestAttemptContent.title) {
    self.bestAttemptContent.title = [NSString stringWithFormat:@"%@", self.bestAttemptContent.title];
  }
  [[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent
  withContentHandler:contentHandler];
}

- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    self.contentHandler(self.bestAttemptContent);
}

@end

The format of Push Notification Service be sent by Server

The content of data can be added or deleted with costume way. if your android device click the push notification bar, and then the app is not opened, the problem must be caused by the format of Push Notification Service. iOS as well.

{
  "message": {
    "notification": {
      "title": "title",
      "body": "message content"
    },
    "token": "fi7FrXMCFeQ:APA91bEZ3CCZEu6NJCzPNyOXq3QoGuCgZ_NZ6pSkuvAYM-VKTvfj1FbnBQKimHaOVqWv_4FD_eGZn1CcfNRf2Ve6X4_mYNwmgI99A1ngxcnY6oyjXTcNRsdIh7YD3SizhRHoTbIXcn-8",
    "data": {
      "image_url": "",
      "push_type": "0",
      "type": "0",
      "url": "MixMatch",
      "push_id": "6587588",
      "send_user_history_id": ""
    },
    "apns": {
      "headers": {
        "apns-priority": "10"
      },
      "payload": {
        "aps": {
          "badge": 1,
          "mutable-content": 1
        }
      },
      "fcm_options": {
        "image": ""
      }
    }
  }
}

Detecting that notification is open or closed when app is in foreground or background.

if we need to detect when our app is coming to the foreground or when it comes to background, the AppState will help me to do it so easy:


import NotificationManager from 'react-native-check-notification-enable'

constructor(props) {
    super(props);
    this.state = {
        loginShow: false,
        loginStatus: false,
        isEnabled: false,
    }
    this.flage = false
}

componentDidMount() {
    AppState.addEventListener('change',this._handleAppStateChange)
    this._navListener = this.props.navigation.addListener('didFocus', () => {

      if (Platform.OS === 'ios') {
        messaging().requestPermission().then((response: any) => {
            if (response === 1) {
                this.setState(prevState => ({
                    isEnabled: true
                }))
            }
            else {
                this.setState(prevState => ({
                    isEnabled: false
                }))
            }
        })
      }
      else {
        NotificationManager.areNotificationsEnabled().then((e)=>{
            if (e === true) {
                this.setState(prevState => ({
                    isEnabled: true
                }))
            }
            else {
                this.setState(prevState => ({
                    isEnabled: false
                }))
            }
          }).catch((e)=>{
            this.setState(prevState => ({
                isEnabled: false
            }))
          })
      }

    })
}

_handleAppStateChange = (nextAppState) => {
    if (nextAppState != null && nextAppState === 'active') {
        //如果是true ,表示从后台进入了前台 ,请求数据,刷新页面。或者做其他的逻辑
        if (this.flage) {
            if (Platform.OS === 'ios') {
                messaging().requestPermission().then((response: any) => {
                    if (response === 1) {
                        this.setState(prevState => ({
                            isEnabled: true
                        }))
                    }
                    else {
                        this.setState(prevState => ({
                            isEnabled: false
                        }))
                    }
                })
            }
            else {
                NotificationManager.areNotificationsEnabled().then((e) => {
                    if (e === true) {
                        this.setState(prevState => ({
                            isEnabled: true
                        }))
                    }
                    else {
                        this.setState(prevState => ({
                            isEnabled: false
                        }))
                    }
                }).catch((e) => {
                    this.setState(prevState => ({
                        isEnabled: false
                    }))
                })
            }
        }
        this.flage = false;
    } else if (nextAppState != null && nextAppState === 'background') {
        this.flage = true;
    }
}


_handleAppStateChange = (nextAppState) => {
    if (nextAppState != null && nextAppState === 'active') {
        //如果是true ,表示从后台进入了前台 ,请求数据,刷新页面。或者做其他的逻辑
        if (this.flage) {
            if (Platform.OS === 'ios') {
                messaging().requestPermission().then((response: any) => {
                    if (response === 1) {
                        this.setState(prevState => ({
                            isEnabled: true
                        }))
                    }
                    else {
                        this.setState(prevState => ({
                            isEnabled: false
                        }))
                    }
                })
            }
            else {
                NotificationManager.areNotificationsEnabled().then((e) => {
                    if (e === true) {
                        this.setState(prevState => ({
                            isEnabled: true
                        }))
                    }
                    else {
                        this.setState(prevState => ({
                            isEnabled: false
                        }))
                    }
                }).catch((e) => {
                    this.setState(prevState => ({
                        isEnabled: false
                    }))
                })
            }
        }
        this.flage = false;
    } else if (nextAppState != null && nextAppState === 'background') {
        this.flage = true;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,743评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,296评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,285评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,485评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,581评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,821评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,960评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,719评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,186评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,516评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,650评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,329评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,936评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,757评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,991评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,370评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,527评论 2 349

推荐阅读更多精彩内容