Expo-notification & Firebase

FE_JACOB 👨🏻‍💻·2022년 5월 12일
0

Firebase cloudFunction 으로 push notification 보내기

Overall

  1. Client 에서 expoPushToken 받기
  2. expoPushTokenFirebase에 저장
  3. CloudFunction 에서 특정 조건에 따라 expo.sendPushNotificationsAsync() 을 사용해서 알림 보내기.

Cada 에서는 사용자가 데이터를 수집하고 리워드를 받습니다.
그리고 리워드를 환전 신청했을때 이체준비가 완료되었다는 알림을 보내기위해서 이번 expo-notification 을 이용해서 구현했습니다.

#Client

사용자의 디바이스에 알림을 허용요청을 할 라이브러리 설치가 필요합니다.
아래 두개를 설치해주세요.

expo-constants
expo-notification

아래 함수는 알림을 허용받고 expoPushTokenreturn 한다.

async function registerForPushNotificationsAsync() {
  let token;
if (Constants.isDevice) {
    const { status: existingStatus } =
      await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;

    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync(); 
      finalStatus = status; // 알림허용을 거절당하면 finalState를 변경
    }

    if (finalStatus !== 'granted') {
      alert('토큰을 가져오지 못했습니다.');
      return;
    }  // 알림허용을 거절당하면 이 조건문에서 return 합니다.

    token = (
      await Notifications.getExpoPushTokenAsync({
        experienceId: 'your experienceId',
      })
    ).data;
    
  } else {
    alert('실제 디바이스를 사용해주세요');
  }

  if (Platform.OS === 'android') { //안드로이드는 세팅을 따로 해주셔야합니다.
    Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#D22F27',
    });
  }

  return token;
}

그 다음은 앱이 시작되었을때 useEffect 를 사용하여 함수를 실행해주고 return 값으로 받은 token을 firebase에 저장해준다.

useEffect(() => {
  registerForPushNotificationsAsync().then(async (token) => {
    try {
      if (token) {
        await db
          .collection('users')
          .doc(currentUser.userID)
          .update({ expoPushToken: token });
      }
    } catch (e) {
      console.log(e);
    }
  });
}, []);

#Server

expo-notification 을 사용하기 위해서 역시 라이브러리 설치가 필요하다.

expo-server-sdk

const { Expo } = require('expo-server-sdk');
const expo = new Expo();

환전신청을 하고 검수가 완료되면 이체준비가 완료되었다는 알림이 가야하기 때문에 특정 조건에 대해 doc을 생성하고 아래 함수를 trigger 시켰습니다.

exports.notificationTrigger = functions.firestore
  .document('users/{usersId}/notifications/{notificationsDocId}')
  .onCreate(async (event, context) => {

    const message = event.data();

    const querySnaps = await db.collection('users').doc(message.userID).get();

    if (querySnaps.data().expoPushToken) {
          return expo.sendPushNotificationsAsync([{
            to: querySnaps.data().expoPushToken,
            sound: 'default',
            title: 'CADA',
            subtitle: `검수가 완료 되었어요👍`,
            body: `1~2시간 이내로 이체 시도가 진행될 예정이예요.`,
            badge: 1,
            data: {
              withSome: 'notification',
            },
            priority: 'high'
          }]);
    }
  });

감사합니다.

profile
단순히 개발자로서 제게 있었던 일을 적는 공간입니다 ✍🏻

0개의 댓글