본문 바로가기

React-native/notification

[ REACT-NATIVE ] 백그라운드에서 헤드업 푸시

참고한 사이트

https://github.com/zo0r/react-native-push-notification

https://github.com/react-native-push-notification/ios

 

GitHub - zo0r/react-native-push-notification: React Native Local and Remote Notifications

React Native Local and Remote Notifications. Contribute to zo0r/react-native-push-notification development by creating an account on GitHub.

github.com

 

필요한 패키지

기본적으로 firebase는 설치가 되어 있는 상황입니다.
 --- firebase 연동과 패키지 설치까지

 

안드로이드 :  react-native-push-notification 패키지 설치

ios :  @react-native-community/push-notification-ios 패키지 설치

 --- 설치 방법은  제일 상단 참고한 사이트에 있습니다.

 

1. index.js 에 셋팅 하기

app.js보다 먼저 실행되는 곳인 index.js에 있어야 정상 작동합니다.

import PushNotificationIOS from "@react-native-community/push-notification-ios";
import PushNotification from "react-native-push-notification";

// Must be outside of any component LifeCycle (such as `componentDidMount`).
PushNotification.configure({
    // (선택) Token 생성 시 호출(iOS 및 Android)
    onRegister: function (token) {
      console.log("TOKEN:", token);
    },
  
    // (필수) remote가 수신 또는 열리거나, 로컬 알림이 열릴 때 호출됩니다.
    onNotification: function (notification) {
      console.log("NOTIFICATION:", notification);
  
      // process the notification
  
      notification.finish(PushNotificationIOS.FetchResult.NoData);
    },
  
    // (선택) Registered Action이 눌리고 invokeApp이 false일 때 호출되며, true인 경우 onNotification이 호출됩니다(Android).
    onAction: function (notification) {
      console.log("ACTION:", notification.action);
      console.log("NOTIFICATION:", notification);
  
      // process the action
    },
  
    // (선택) 사용자가 원격 알림 등록에 실패하면 호출됩니다. 일반적으로 APNS에 문제가 있거나 장치가 시뮬레이터일 때 발생합니다. (iOS)
    onRegistrationError: function(err) {
      console.error(err.message, err);
    },
  
    // IOS ONLY (선택): default: all - Permissions to register.
    permissions: {
      alert: true,
      badge: true,
      sound: true,
    },
  
    // 초기 알림이 자동으로 팝업되어야 하는 경우
    // default: true
    popInitialNotification: true,
  
    /**
     * (선택) 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,
  });

 

2. 백그라운드에서 헤드업 푸시

2.1.  채널 생성

채널이 없으면 알림이 작동하지 않습니다.

편의를 위해 저는 푸시를 관리하는 PushCenter.js 만들어서 불러오는 식으로 해볼게요

// PushCenter.js

import PushNotification from 'react-native-push-notification';

PushNotification.createChannel(
  {
    channelId: 'Normal',
    channelName: 'Normal',
    channelDescription: 'Notification for Normal message',
    importance: 4,
    vibrate: true,
  },
  created => console.log(`createChannel returned '${created}'`),
);
export const Normal_Notification = remoteMessage => {
  console.log('Normal remoteMessage', remoteMessage);
  PushNotification.localNotification({
    channelId: 'Normal',
    seq: remoteMessage.data.seq,
    push_type: remoteMessage.data.push_type,
    hseq: remoteMessage.data.applicant_seq,
    title: remoteMessage.data.title,
    message: remoteMessage.data.body,
    status: remoteMessage.data.status,
    from_id: remoteMessage.data.from_id,
    userid: remoteMessage.data.to_id,
  });
};

 

2.2 background handler에 호출

// index.js

import { Normal_Notification } from './PushCenter';

// 푸시알림 : 백그라운드 핸들러
messaging().setBackgroundMessageHandler(async remoteMessage => {
  console.log('Message handled in the background!', remoteMessage);

  Normal_Notification(remoteMessage);
});

 

2.3 서버에서 푸시 보내기
저는 백엔드에서 Php로 푸시 보내는 테스트 파일을 만들어서 보냈어요

 

혹시나 안되는 경우는 설정이 잘 되어 있는지 확인하고 다시 빌드해주시면 됩니다.