FCM으로 react-native notification 구현하기

뱀기·2022년 12월 6일
1

Nurihaus

목록 보기
9/13

내가 또 다시 설정하기 귀찮아서 정리를 하려고 한다!

  • apns, firebase 연결은 다른 글들에서 많이 있으니 뺴고, 그 이후 코드 작성 부분을 쓰겠당.
  • Device permission
// 리턴값의 true, false에 따라 다음 동작을 실행한다.
const requestUserPermission = async () => {
  await notifee.requestPermission();

  const authStatus = await messaging().requestPermission();
  const enabled =
    authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL;

  return enabled;
};
  • Get token
// 허가를 받은 경우 토큰을 발급한다.
const resisterForPushNotificationsAsync = async () => {
    return requestUserPermission().then(async (enabled) => {
      if (enabled) {
        if (Platform.OS === 'ios') {
          // ios의 경우 필수가 아니라고도 하고 필수라고도 하고.. 그냥 넣어버렸다.
          messaging().registerDeviceForRemoteMessages();
        }
        return await messaging().getToken()
      }
    });
};
  • Remote message notifee이용해서 띄우기

// 공식문서 https://notifee.app/
// displayNotification 설정을 android, ios따로 해주면 노출될 알림을 커스텀할 수 있다.
import notifee from '@notifee/react-native';
import messaging from '@react-native-firebase/messaging';

async function onMessageReceived(message) {
 	notifee.displayNotification(JSON.parse(message.data.notifee));
}
// foregound에서
messaging().onMessage(onMessageReceived);
// 꺼진 상태에서
messaging().setBackgroundMessageHandler(onMessageReceived);
  • 이후 발급받은 토큰을 보관해놨다가 사용하면 된다.
// 아래를 주의해서 postman으로 실험해보면 잘 연결됐는지 확인 할 수 있다.

post https://fcm.googleapis.com/fcm/send

headers에 Authorization: key={FCMServerKey}

body

{
    "to": 위에서 발급했던 토큰,
    "notification" :{
        "title" : "title",
        "body" : "body"
    },
    "data":{
        "title" : "title",
        "body" : "body"
    }
}

기타

  • FCM 특정 topic scribe, unscribe
const subscribeTopic = async (topic: string) => {
  messaging()
    .subscribeToTopic(topic)
    .then(() => console.log('subscribed to topic:', topic))
    .catch((err) => {
      throw err;
    });
};
const unSubscribeTopic = async (topic: string) => {
  messaging()
    .unsubscribeFromTopic(topic)
    .then(() => console.log('unsubscribed to topic:', topic))
    .catch((err) => {
      throw err;
    });
};
  • 특정 유저 FCM topic 확인 방법
get
headers는 위와 같음.
https://iid.googleapis.com/iid/info/${발급했던 FCM 토큰}?details=true
  • 특정 topic에 알림 보내기
위 알림 보내기에서 to: "/topics/myTopic" 으로 변경
구독한 유저들에게 발송된다.
  • notification 오픈 시 action
messaging().onNotificationOpenedApp(안에 fn을 넣으면 된다.);

getApsToken인가 암튼 이게 있어서 한참을 고생했는데 FCM과 상호작용을 하려면 getToken으로 발급된 토큰을 사용하여야한다. APNS와 소통하는 전용 토큰이라 IOS인 경우 두가지 토큰을 다 받아서 사용하도록 했음.

1개의 댓글

comment-user-thumbnail
2023년 2월 2일

background에서 fcm 알람하고 notifee 알람이 2개가 같이 오는데 어떻게 해결하셨나요?

답글 달기