Dandy Now!
  • [React Native] Expo 푸시 알림 완벽 정복 튜토리얼
    2025년 07월 18일 14시 49분 59초에 업로드 된 글입니다.
    작성자: DandyNow
    728x90
    반응형

    Expo 푸시 알림 완벽 정복 튜토리얼

    이 튜토리얼은 Expo의 푸시 알림 서비스를 사용하여 React Native 애플리케이션에 푸시 알림 기능을 통합하는 전체 과정을 안내합니다. 기본 개념 이해부터 실제 구현, 전송 및 수신 처리까지 모든 단계를 다룹니다.


    1. 소개: Expo 푸시 알림 서비스란?

    Expo 푸시 알림 서비스는 개발자가 Apple(APNs) 및 Google(FCM)의 푸시 알림 서비스를 직접 다루는 복잡성을 줄여주는 중개 서비스입니다. 이 서비스를 통해 iOS와 Android 플랫폼에 대해 동일한 방식으로 알림을 보낼 수 있어 개발 시간을 크게 단축할 수 있습니다.

    주요 이점:

    • 플랫폼 간 통일성: 단일 API로 Android와 iOS에 모두 알림을 보낼 수 있습니다.
    • 간소화된 설정: 복잡한 네이티브 설정을 Expo가 상당 부분 자동화합니다.
    • 서버 구현 용이성: Expo에서 제공하는 다양한 언어의 서버 SDK를 통해 쉽게 백엔드를 구축할 수 있습니다.

    참고: 푸시 알림은 안드로이드 에뮬레이터나 iOS 시뮬레이터에서 작동하지 않으므로, 반드시 실제 기기로 테스트해야 합니다.

    2. 핵심 개념: 푸시 알림 이해하기

    구현에 앞서 몇 가지 주요 개념을 이해해야 합니다.

    • 푸시(원격) 알림 vs 로컬 알림:
      • 푸시 알림: 서버에서 사용자 기기로 보내는 알림입니다. 이 튜토리얼의 주요 내용입니다.
      • 로컬 알림: 앱 내부에서 특정 시간에 예약하여 생성되는 알림입니다.
    • 앱 상태에 따른 동작:
      • 포그라운드 (Foreground): 앱이 화면에 열려 활성화된 상태. 이 때 수신된 알림은 앱 내부에서 직접 처리 방법을 제어할 수 있습니다.
      • 백그라운드 (Background): 앱이 최소화되어 화면에 보이지 않지만 실행 중인 상태. 일반적으로 OS가 알림을 표시합니다.
      • 종료 (Terminated): 앱이 완전히 종료된 상태. OS가 알림을 표시하며, 사용자가 알림을 탭하면 앱이 실행됩니다.
    • 푸시 알림 유형:
      • 알림 메시지 (Notification Message): 제목, 본문 등 표시할 정보를 포함하는 가장 일반적인 알림입니다.
      • 데이터 메시지 (Data-only Notification): 사용자에게 보이지 않는 JSON 데이터를 포함하며, 앱의 백그라운드 작업을 트리거하는 데 사용됩니다. (iOS에서는 "Background Notification"에 해당)

    3. 클라이언트 설정: 권한 요청 및 토큰 발급

    푸시 알림을 받기 위해 클라이언트 앱에서 사용자의 허가를 받고, 각 기기를 식별할 수 있는 고유한 ExpoPushToken을 발급받아야 합니다.

    1단계: 필요 라이브러리 설치

    프로젝트에 필요한 라이브러리를 설치합니다.

    npx expo install expo-notifications expo-device expo-constants
    • expo-notifications: 알림 권한 요청, 토큰 발급, 알림 수신/상호작용 처리를 담당합니다.
    • expo-device: 앱이 실제 기기에서 실행 중인지 확인하는 데 사용됩니다.
    • expo-constants: 앱 설정(app.json)에 접근하여 projectId를 가져오는 데 사용됩니다.

    2단계: 권한 요청 및 푸시 토큰 발급 코드 작성

    다음은 푸시 알림을 등록하고 토큰을 가져오는 최소 기능의 예제 코드입니다. App.tsx 파일에 적용해볼 수 있습니다.

    import { useState, useEffect, useRef } from 'react';
    import { Text, View, Button, Platform } from 'react-native';
    import * as Device from 'expo-device';
    import * as Notifications from 'expo-notifications';
    import Constants from 'expo-constants';
    
    // 앱이 포그라운드 상태일 때 알림 처리 방법 설정
    Notifications.setNotificationHandler({
      handleNotification: async () => ({
        shouldShowAlert: true,
        shouldPlaySound: false,
        shouldSetBadge: false,
      }),
    });
    
    // 푸시 토큰을 발급받는 함수
    async function registerForPushNotificationsAsync() {
      let token;
    
      if (Platform.OS === 'android') {
        await Notifications.setNotificationChannelAsync('default', {
          name: 'default',
          importance: Notifications.AndroidImportance.MAX,
          vibrationPattern: [0, 250, 250, 250],
          lightColor: '#FF231F7C',
        });
      }
    
      if (Device.isDevice) {
        const { status: existingStatus } = await Notifications.getPermissionsAsync();
        let finalStatus = existingStatus;
        if (existingStatus !== 'granted') {
          const { status } = await Notifications.requestPermissionsAsync();
          finalStatus = status;
        }
        if (finalStatus !== 'granted') {
          alert('Failed to get push token for push notification!');
          return;
        }
        // EAS 프로젝트 ID를 사용하여 토큰을 가져옵니다.
        const projectId = Constants.expoConfig?.extra?.eas?.projectId;
        if (!projectId) {
          alert('Project ID not found. Make sure you have configured it in app.json');
          return;
        }
        token = (await Notifications.getExpoPushTokenAsync({ projectId })).data;
        console.log(token);
      } else {
        alert('Must use physical device for Push Notifications');
      }
    
      return token;
    }
    
    
    export default function App() {
      const [expoPushToken, setExpoPushToken] = useState('');
      const [notification, setNotification] = useState<Notifications.Notification | false>(false);
      const notificationListener = useRef<Notifications.Subscription>();
      const responseListener = useRef<Notifications.Subscription>();
    
      useEffect(() => {
        registerForPushNotificationsAsync().then(token => setExpoPushToken(token ?? ''));
    
        // 앱이 실행 중일 때 알림을 수신하면 발생하는 리스너
        notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
          setNotification(notification);
        });
    
        // 사용자가 알림을 탭하는 등 상호작용했을 때 발생하는 리스너
        responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
          console.log(response);
        });
    
        return () => {
          if (notificationListener.current) {
            Notifications.removeNotificationSubscription(notificationListener.current);
          }
          if (responseListener.current) {
            Notifications.removeNotificationSubscription(responseListener.current);
          }
        };
      }, []);
    
      return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'space-around' }}>
          <Text>Your Expo push token: {expoPushToken}</Text>
          <View style={{ alignItems: 'center', justifyContent: 'center' }}>
            <Text>Title: {notification && notification.request.content.title} </Text>
            <Text>Body: {notification && notification.request.content.body}</Text>
            <Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
          </View>
        </View>
      );
    }

    4. 자격 증명 설정: Android (FCM) 및 iOS (APNs)

    Expo 푸시 서비스를 사용하려면, 각 플랫폼에 대한 자격 증명을 설정하고 EAS(Expo Application Services)에 업로드해야 합니다.

    Android (FCM V1 설정)

    1. Firebase 프로젝트 생성: Firebase Console에서 새 프로젝트를 만들거나 기존 프로젝트를 사용합니다.
    2. 서비스 계정 키 생성:
      • Firebase 프로젝트 설정 > 서비스 계정 탭으로 이동합니다.
      • 새 비공개 키 생성 버튼을 클릭하여 .json 형식의 서비스 계정 키 파일을 다운로드합니다. 이 파일은 민감한 정보를 담고 있으므로 안전하게 보관해야 합니다.
    3. EAS에 키 업로드:
      • 프로젝트 루트에서 eas credentials 명령을 실행합니다.
      • Android를 선택하고, Google Service Account Key 관련 메뉴를 따라 다운로드한 .json 파일을 업로드합니다.
    4. google-services.json 설정:
      • Firebase 프로젝트 설정 > 일반 탭에서 Android 앱을 등록하고 google-services.json 파일을 다운로드합니다.
      • 다운로드한 파일을 프로젝트 루트에 배치하고, app.json에 경로를 지정합니다.
      // app.json
      {
        "expo": {
          // ...
          "android": {
            // ...
            "googleServicesFile": "./google-services.json"
          }
        }
      }

    iOS (APNs 설정)

    iOS는 유료 Apple Developer 계정이 필요합니다.

    1. EAS CLI로 자동 설정:
      • eas build 또는 eas credentials 명령을 처음 실행할 때, EAS CLI가 푸시 알림 설정 여부를 묻습니다.
      • Setup Push Notifications for your project? 질문에 Yes로 답하면 EAS가 자동으로 Apple Push Notification service(APNs) 키를 생성하고 서버에 등록합니다.

    개발 빌드 생성

    자격 증명 설정이 완료되면, 실제 기기에서 테스트할 개발 빌드를 생성해야 합니다.

    eas build --profile development --platform all

    5. 서버 구현: 푸시 알림 전송하기

    클라이언트에서 얻은 ExpoPushToken을 서버로 전송하여 데이터베이스에 저장한 뒤, 필요할 때 이 토큰을 사용해 Expo Push API로 알림을 보냅니다.

    API 엔드포인트

    • URL: https://exp.host/--/api/v2/push/send
    • Method: POST
    • Headers: Content-Type: application/json

    간단한 전송 예시 (cURL)

    curl -H "Content-Type: application/json" -X POST "https://exp.host/--/api/v2/push/send" -d '{
      "to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
      "title":"Hello",
      "body": "World"
    }'

    푸시 티켓과 푸시 영수증

    신뢰성 있는 알림 전송을 위해 푸시 티켓(Push Ticket)푸시 영수증(Push Receipt) 개념을 이해해야 합니다.

    1. 전송 및 티켓 수신:
      • push/send API로 알림을 보내면, Expo 서버는 즉시 푸시 티켓을 응답으로 보냅니다.
      • 티켓의 statusok이면 Expo 서버에 정상적으로 접수되었다는 의미입니다. (기기 도착 보장은 아님)
      • 티켓에는 id가 포함되는데, 이 ID로 나중에 최종 결과를 조회할 수 있습니다.
    2. 영수증 확인:
      • Expo 서버가 APNs/FCM으로 알림 전달을 시도한 후, 그 결과가 푸시 영수증으로 기록됩니다.
      • push/getReceipts API에 티켓 ID 배열을 보내 영수증을 조회합니다.
      • 영수증의 status를 통해 최종 성공 여부나 DeviceNotRegistered(더 이상 유효하지 않은 토큰)와 같은 오류를 확인할 수 있습니다.

    Expo는 Node.js, Python, Ruby 등 다양한 언어를 위한 서버 SDK를 제공하므로, 이를 사용하면 티켓/영수증 처리, 재시도 로직 등을 더 쉽게 구현할 수 있습니다.

    6. 클라이언트 구현: 수신된 알림 처리하기

    expo-notifications 라이브러리의 리스너를 사용하여 수신된 알림에 반응하고 상호작용을 처리합니다.

    • addNotificationReceivedListener: 앱이 포그라운드 상태일 때 알림이 도착하면 호출됩니다. 앱 내에서 커스텀 UI를 보여주는 등의 처리를 할 수 있습니다.
    • addNotificationResponseReceivedListener: 사용자가 알림을 했을 때 호출됩니다. (앱이 포그라운드, 백그라운드, 종료된 상태 모두에서 작동). 특정 화면으로 이동시키거나, 알림에 포함된 데이터에 따라 특정 작업을 수행하는 데 사용됩니다.
    • setNotificationHandler: 앱이 포그라운드 상태일 때 알림이 도착했을 때 OS 레벨의 동작(알림 배너 표시, 소리 재생 등)을 제어합니다. null을 반환하면 아무 일도 일어나지 않습니다.
    // 예시: 사용자가 알림을 탭하면 'details' 화면으로 이동
    useEffect(() => {
      const subscription = Notifications.addNotificationResponseReceivedListener(response => {
        const data = response.notification.request.content.data;
        // data.url 등을 확인하여 특정 화면으로 네비게이션
        if (data.screen) {
          navigation.navigate(data.screen);
        }
      });
      return () => subscription.remove();
    }, []);

    7. 자주 묻는 질문 (FAQ)

    • Q: 토큰은 만료되나요?
      • A: 일반적으로 Expo Push Token은 만료되지 않습니다. 하지만 사용자가 앱을 삭제 후 재설치하거나, 앱 데이터를 지우거나, OS를 업데이트하는 등의 경우 변경될 수 있습니다. DeviceNotRegistered 오류를 수신하면 해당 토큰을 서버에서 삭제해야 합니다.
    • Q: 알림 배지 카운트는 어떻게 관리하나요?
      • A: 알림 페이로드에 badge 숫자를 포함하여 보낼 수 있습니다. 앱에서는 getBadgeCountAsync()setBadgeCountAsync()를 사용하여 배지 카운트를 읽고 업데이트할 수 있습니다.
    • Q: 알림 전송이 지연되거나 실패하는 이유는 무엇인가요?
      • A: 네트워크 문제, APNs/FCM 서비스의 일시적 장애, 잘못된 자격 증명, DeviceNotRegistered 토큰으로의 전송 시도 등 다양한 원인이 있을 수 있습니다. 푸시 영수증을 확인하여 정확한 원인을 파악하는 것이 중요합니다.

    이 튜토리얼이 Expo 푸시 알림 기능을 구현하는 데 도움이 되기를 바랍니다.

    참조 문서: Expo push notifications (https://docs.expo.dev/push-notifications/overview/)


    728x90
    반응형
    댓글