Skip to main content

Push-Notification in React-native



Implimenting Push-notification in React-native


Note: To send push notification you have to implement firebase first for implementing firebase check my previour blog
1. Install Package = @react-native-firebase/messaging,


2.FcmService.js                                                                                        
import messaging from '@react-native-firebase/messaging';
import {Platformfrom 'react-native';

class FCMService {

   register = (onRegisteronNotificationonOpenNotification=>{
       this.checkPermission(onRegister)
       this.createNotificationListeners(onRegisteronNotificationonOpenNotification)
   }
   registerAppWithFCM = async() => {
       if(Platform.OS === 'ios'){
        await messaging().registerDeviceForRemoteMessages();
        await messaging.setAutoInitEnabled(true)
       }
      
   }
   checkPermission = (onRegister=> {
       messaging().hasPermission()
       .then(enabled => {
           if(enabled){
               // Use Has Permissions
               this.getToken(onRegister)
           }
           else{
               //user dont have permission
               this.requestPermission(onRegister)
           }
       }).catch(error => {
           console.log("[FCMService] permission rejected",error);
            })
       }

       getToken = (onRegister=> {
           messaging().getToken()
           .then(fcmToken => {
               if(fcmToken){
                   onRegister(fcmToken)
               }else{
                   console.log("[FCMService] User Does not have a device token")
               }
           }).catch(error => {
            console.log("[FCMService] getToken rejected",error);
           })
       }
    
    requestPermission = (onRegister=> {
            messaging().requestPermission()
            .then(() => {
                this.getToken(onRegister)
            }).catch(error => {
                console.log("[FCMService] Request Permission rejected",error);
            })
        }
    deleteToken = () => {
        console.log("[FCMService] deleteToken")
        messaging().deleteToken()
        .catch(error => {
            console.log("[FCMService] Delete Token error",error);
        })
    }

    createNotificationListeners = (onRegisteronNotificationonOpenNotification=> {
        //when the application is running but in background
        messaging()
        .onNotificationOpenedApp(remoteMessage => {
            console.log("[FCMService] onNotificationOpendApp Notification Cauesd app to open error");
            if(remoteMessage) {
                const notification = remoteMessage.notification
                onOpenNotification(notification)
                //this.
            }
        });

        //when the application is opened from a quit state.
        messaging()
        .getInitialNotification()
        .then(remoteMessage => {
            console.log("[FCMService] getInitialNotification Notification Cauesd app to open error");
            if(remoteMessage){
                const notification = remoteMessage.notification
                onOpenNotification(notification)
            }
        });

        //forgrounnd state messages
        this.messageListener = messaging().onMessage(async remoteMessage => {
            console.log("[FCMService] A new FCm message arrived",remoteMessage);
            if(remoteMessage){
                let notification = null
                if(Platform.OS === 'ios'){
                    notification = remoteMessage.data.notification
                }else{
                    notification = remoteMessage.notification
                }
                onNotification(notification)
            }
        });

        //Triggerd When have new token
        messaging().onTokenRefresh(fcmToken => {
            console.log("[FCMService] new token refresh",fcmToken);
        })
    }
    unRegister = () => {
        this.messageListener()
    };
}

export const fcmService = new FCMService() 

3.LocalNotificationService.js
import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from "@react-native-community/push-notification-ios";
import  {Platformfrom 'react-native';

class LocalNotificationService {
    configure = (onOpenNotification=> {
        PushNotification.configure({
            // (optional) Called when Token is generated (iOS and Android)
            onRegister: function (token) {
            //  console.log("[LocalNotificationService] onRegister:", token);
            },
            onNotification: function (notification) {
             //   console.log("[LocalNotificationService] onNotification:", notification);
                if(!notification?.data){
                    return
                }
                notification.userInteraction = true;
                onOpenNotification(Platform.OS === 'ios' ? notification.data.item : notification.data);
                // process the notification
             if(Platform.OS === 'ios'){
                 notification.finish(PushNotificationIOS.FetchResult.NoData)
             }
              },
              permissions: {
                alert: true,
                badge: true,
                sound: 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
   * - if you are not using remote notification or do not have Firebase installed, use this:
   *     requestPermissions: Platform.OS === 'ios'
   */
  requestPermissions: true,
    });
}
unRegister = () => {
    PushNotification.unregister()
}

    showNotification = ( idtitlemessagedata = {},option = {}) => {
        PushNotification.localNotification({

        ...this.buildAndroidNotification(id,title,message,data,option),
        ...this.buildIOSNotification(id,title,message,data,option),
        title:title || "",
        message:message||"",
        playSound:option.playSound || false,
     soundName:option.soundName || 'default',
     userInteraction:false //Boolen
    
    });

}
buildAndroidNotification = (idtitlemessagedata = {},option = {}) => {
    return {
        id:id,
        autoCancel: true,
        largeIcon: option.largeIcon || "ic_launcher",
        smallIcon: option.smallIcon ||"ic_stat_ic_notification"
        bigText: message || ""// (optional) default: "message" prop
        subText: title || "",
        vibrate: option.vibrate || true// (optional) default: true
        vibration: option.vibration ||300,
        priority: option.priority ||"high"
        importance: option.importance ||"high"
        data:data,
    }
}
buildIOSNotification = (idtitlemessagedata = {},option = {}) => {
    return {
       alertAction:option.alertAction || 'view',
       category:option.category || "",
       userInfo: {
           id:id,
           item:data,
       }
    }
}
cancelAllLocalNotifications = () => {
    if(Platform.OS === 'ios'){
        PushNotificationIOS.removeAllDeliveredNotifications();

    }else{
        PushNotification.cancelAllLocalNotifications();
    }
}

  removeAllDeliveredNotificationByID = (notificationId=> {
   // console.log("[LocalNotificationService] removeAllDeliveredNotificationByID:", notificationId);
    PushNotification.cancelLocalNotifications({id:`${notificationId}`})
  }

}

export const localNotificationService = new LocalNotificationService()

4.For knowing fcm token =>
   messaging().getToken()
        .then(fcmToken => {
            console.log(fcmToken)
           this.setState({fcmtoken:fcmToken})
        }).catch(error => {
         console.log("[FCMService] getToken rejected",error);
        })
5.Index.js
/**
 * @format
 */
import React from 'react'
import {AppRegistryfrom 'react-native';
import App from './App';
import {name as appNamefrom './app.json';
import messaging from '@react-native-firebase/messaging'

messaging().setBackgroundMessageHandler(async remoteMessage => {
    console.log('Message handled in the background!'remoteMessage);
  });

  function HeadlessCheck({ isHeadless }) {
    if (isHeadless) {
      // App has been launched in the background by iOS, ignore
      return null;
    }
  
    return <App />;
  }
  
AppRegistry.registerComponent(appName, () => HeadlessCheck)

Comments

Popular posts from this blog

Why Use React Native for Your Mobile App Devlopment?

React Native the same code is used for deployment both on iOS and Android platforms.  It means that it’s possible to get an app for two platforms at once — iOS and Android. React Native shortens the development cycle, makes it possible to deliver products in the fastest way. Development of apps is adapted to the hybrid environment and has native results. The framework uses famous ReactJS UI library developed by Facebook for user interfaces and apps creating and implements ReactJS under the hood. It transfers virtual DOM, improved app performance, and more simple programming processes from ReactJS. A built mobile app is smoother and is loaded much faster than a classic hybrid one. As JavaScript interacts asynchronously with the native environment, UI feels fluid and is highly responsive. A single code base is deployed to multiple mobile operating systems. Components are reused anytime at any level into existing code without you rewriting it and recompiling the app.

React Native CLI Vs Expo what to use?

React Native CLI  vs Expo :New React Native Apps. If you’ve decided that React Native is right for your project, this article is for you! We will be cover your options for bootstrapping your app, and the pros and cons for each option. There are two methods for initializing and developing your app: Expo, and the React Native CLI. Until recently there was a distinct third method, using Create React Native App (CRNA). CRNA has since been merged with the Expo project, and only continues to exist as a separate entity to provide backwards compatibility. Expo falls into the first category of tools, providing a more robust and developer friendly development workflow at the cost of some flexibility. Apps bootstrapped with Expo also have access to a slew of useful features provided by the Expo SDK, like  BarcodeScanner ,  MapView ,  ImagePicker , and so many more. Initializing an app with the React Native CLI, via the  react-native init  command provides flexibility ...

How to use Axios In React-native

  Axios Is used For Api Calling in React-native ... Step 1.  npm install axios; After installing package. import axios from "axios"; const options = {         method:method   // post or get         headers:{'content-type':'application/json'},         data:data,         url:"Apiurl",     };     axios(options).then(res => {             //Do something     } Note If u Want to Send Form-data then  change Content-type to multiformdata and pass formdata in data field in Options