반응형
Jake Seo
제이크서 위키 블로그
Jake Seo
전체 방문자
오늘
어제
  • 분류 전체보기 (715)
    • 일상, 일기 (0)
    • 백준 문제풀이 (1)
    • 릿코드 문제풀이 (2)
    • 알고리즘 이론 (10)
      • 기본 이론 (2)
      • 배열과 문자열 (8)
    • 데이터베이스 (15)
      • Planet Scale (1)
      • MSSQL (9)
      • 디비 기본 개념 (1)
      • SQLite 직접 만들어보기 (4)
    • 보안 (7)
    • 설계 (1)
    • 네트워크 (17)
      • HTTP (9)
      • OSI Layers (5)
    • 회고 (31)
      • 연간 회고 (2)
      • 주간 회고 (29)
    • 인프라 (52)
      • 도커 (12)
      • AWS (9)
      • 용어 (21)
      • 웹 성능 (1)
      • 대규모 서비스를 지탱하는 기술 (9)
    • 깃 (7)
    • 빌드 도구 (7)
      • 메이븐 (6)
      • 그레이들 (0)
    • Java (135)
      • 이펙티브 자바 (73)
      • 자바 API (4)
      • 자바 잡지식 (30)
      • 자바 디자인 패턴 (21)
      • 톰캣 (Tomcat) (7)
    • 프레임워크 (64)
      • next.js (14)
      • 스프링 프레임워크 (28)
      • 토비의 스프링 (6)
      • 스프링 부트 (3)
      • JPA (Java Persistence API) (5)
      • Nest.js (8)
    • 프론트엔드 (48)
      • 다크모드 (1)
      • 노드 패키지 관리 매니저 (3)
      • CSS (19)
      • Web API (11)
      • tailwind-css (1)
      • React (5)
      • React 새 공식문서 요약 (1)
      • HTML (Markup Language) (5)
    • 자바스크립트 (108)
      • 모던 자바스크립트 (31)
      • 개념 (31)
      • 정규표현식 (5)
      • 코드 스니펫 (1)
      • 라이브러리 (6)
      • 인터뷰 (24)
      • 웹개발자를 위한 자바스크립트의 모든 것 (6)
      • 팁 (2)
    • Typescript (49)
    • 리눅스와 유닉스 (10)
    • Computer Science (1)
      • Compiler (1)
    • IDE (3)
      • VSCODE (1)
      • IntelliJ (2)
    • 세미나 & 컨퍼런스 (1)
    • 용어 (개발용어) (16)
      • 함수형 프로그래밍 용어들 (1)
    • ORM (2)
      • Prisma (2)
    • NODEJS (2)
    • cypress (1)
    • 리액트 네이티브 (React Native) (31)
    • 러스트 (Rust) (15)
    • 코틀린 (Kotlin) (4)
      • 자바에서 코틀린으로 (4)
    • 정규표현식 (3)
    • 구글 애널리틱스 (GA) (1)
    • SEO (2)
    • UML (2)
    • 맛탐험 (2)
    • 리팩토링 (1)
    • 서평 (2)
    • 소프트웨어 공학 (18)
      • 테스팅 (16)
      • 개발 프로세스 (1)
    • 교육학 (1)
    • 삶의 지혜, 통찰 (1)
    • Chat GPT (2)
    • 쉘스크립트 (1)
    • 컴파일 (2)
    • Dart (12)
    • 코드팩토리의 플러터 프로그래밍 (4)
    • 플러터 (17)
    • 안드로이드 스튜디오 (1)
    • 윈도우즈 (1)
    • 잡다한 백엔드 지식 (1)
    • 디자인 패턴 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 자바스크립트 면접
  • 프로그래머의 뇌
  • prerendering
  • 자료구조
  • 자바 검증
  • 토비의 스프링
  • 외래키 제약조건
  • item7
  • next js app
  • 자바스크립트 인터뷰
  • item8
  • 플라이웨이트패턴
  • 추상 팩터리 패턴
  • 싱글톤
  • 작업기억공간
  • 슬로우 쿼리
  • rust
  • 자바 디자인패턴
  • 메이븐 라이프사이클
  • Java
  • 빈 검증
  • 서버리스 컴퓨팅
  • 메이븐 페이즈
  • 느린 쿼리
  • pnpm
  • 이펙티브 자바 item9
  • Next.js
  • 도커공식문서
  • bean Validation
  • 러스트
  • 객체복사
  • 자바스크립트
  • NEXT JS
  • 알고리즘
  • MSSQL
  • Pre-rendering
  • 메이븐 골
  • 팩터리 메서드 패턴
  • try-with-resources
  • 참조 해제
  • 이펙티브자바
  • item9
  • 싱글톤 패턴
  • 스프링 검증
  • 디자인패턴
  • Javadoc 자바독 자바주석 주석 Comment
  • serverless computing
  • 자바
  • 싱글턴
  • 이펙티브 자바

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Jake Seo

제이크서 위키 블로그

리액트 네이티브 푸시 알람 보내는 방법
리액트 네이티브 (React Native)

리액트 네이티브 푸시 알람 보내는 방법

2022. 11. 19. 20:58

개요

리액트 네이티브에서 푸시 알람을 보내는 방법을 알아보자.

푸시 알람의 종류

푸시 알람의 종류는 2가지가 있다.

로컬 푸시 알람

푸시 서버를 타지 않고, 앱 자체에서 폰으로 보내는 푸시 알람이다.

로컬 알람도 아래에서 설치하게 될 react-native-push-notification 패키지를 통해 보낼 수 있다.
그러므로 로컬 알람과 원격 알람을 따로 설정할 필요 없다.

원격 푸시 알람

푸시 서버를 타고 보내는 푸시 알람이다. 요즘은 FCM (Firebase Cloud Messaging) 이라는 도구를 이용해 푸시 알람을 보내는 것이 일반적이다.

푸시 알람 개발 프로세스

  • 리액트 네이티브에 알맞은 푸시알람 npm 패키지 설치
  • FCM (Firebase Cloud Messaging) 에서 키 발급
  • build.gradle 을 통해 알맞은 패키지 설치
  • AndroidManifest.xml 파일 내부에 푸시알람에 필요한 설정 해주기
  • 푸시알람 소스코드 작성하기

npm 패키지 설치

# 안드로이드
npm i @react-native-firebase/analytics @react-native-firebase/app @react-native-firebase/messaging
# IOS
npm i react-native-push-notification @react-native-community/push-notification-ios
# Typescript
npm i -D @types/react-native-push-notification
npx pod-install

IOS 와 Android 둘 다 결국 FCM (Firebase Cloud Messaging) 을 사용하는 것이 정신건강에 이롭다.

주의: react-native-pusn-notification 패키지를 깔았음을 정확히 인지해야 한다. 비슷한 이름의 react-native-notifications 와 헷갈리면 안 된다.

FCM 이란?

푸시 알람을 편리하게 보낼 수 있도록 해주는 도구라고 생각하면 된다.

위와 같은 과정을 통해 FCM 으로 푸시 알람을 보내게 된다.

FCM 을 이용하기 위해 일련의 절차를 거쳐야 하는데, Firebase Cloud Messaging 키 발급 방법 블로그를 보고 따라하면 된다.

build.gradle 등 설정

이 링크 에서 README.md 문서가 시키는대로 하면 된다.

소스코드 작성

App.tsx 에서 푸시 서버 관련 설정해주기

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

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

PushNotification.configure({
  // (optional) 토큰이 생성될 때 실행됨(토큰을 서버에 등록할 때 쓸 수 있음)
  // token 을 서버로 보내야 서버가 내가 누군지 알 수 있다. 서버가 이용자의 휴대폰 고유 토큰을 저장해두었다가, 푸시 알림을 통해 알림이 간다.
  onRegister: function (token: any) {
    console.log("TOKEN:", token);
  },

  // (required) 리모트 노티를 수신하거나, 열었거나 로컬 노티를 열었을 때 실행
  // 알림이 와서 알림을 클릭했을 때 실행되는 부분
  onNotification: function (notification: any) {
    console.log("NOTIFICATION:", notification);
    if (notification.channelId === "riders") {
      // 아이폰 안드로이드에 따라 .data.message 냐 .message 냐가 갈림
      // if (notification.message || notification.data.message) {
      // 푸시 알람으로 온 메세지를 한번 더 보여줌
      //   store.dispatch(
      //     userSlice.actions.showPushPopup(
      //       notification.message || notification.data.message,
      //     ),
      //   );
      // }
    }
    // process the notification

    // (required) 리모트 노티를 수신하거나, 열었거나 로컬 노티를 열었을 때 실행
    // 아이폰쪽에서 그냥 필요함
    notification.finish(PushNotificationIOS.FetchResult.NoData);
  },

  // (optional) 등록한 액션을 누렀고 invokeApp이 false 상태일 때 실행됨, true면 onNotification이 실행됨 (Android)
  onAction: function (notification: any) {
    console.log("ACTION:", notification.action);
    console.log("NOTIFICATION:", notification);

    // process the action
  },

  // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
  onRegistrationError: function (err: Error) {
    console.error(err.message, err);
  },

  // IOS ONLY (optional): default: all - Permissions to register.
  permissions: {
    alert: true,
    badge: true,
    sound: true,
  },

  // Should the initial notification be popped automatically
  // default: 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,
});

// 채널을 통해 푸시알람에 대한 디테일한 설정이 가능하다.
// 공지사항용, 광고용, 단순 알람용 등등 ..
// 유저는 특정 채널을 수신 거부하는 등의 개별 설정이 가능하다.
PushNotification.createChannel(
  {
    channelId: "riders", // (required)
    channelName: "앱 전반", // (required)
    channelDescription: "앱 실행하는 알림", // (optional) default: undefined.
    soundName: "default", // (optional) See `soundName` parameter of `localNotification` function
    importance: 4, // (optional) default: 4. Int value of the Android notification importance
    vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
  },
  (created: boolean) =>
    console.log(`createChannel riders returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
);

폰 토큰 저장하기

// 토큰 설정
useEffect(() => {
  async function getToken() {
    try {
      // 기기 등록이 안되어있다면, 기기 토큰을 먼저 등록해야 한다.
      if (!messaging().isDeviceRegisteredForRemoteMessages) {
        await messaging().registerDeviceForRemoteMessages();
      }

      // 토큰 가져오기
      const token = await messaging().getToken();
      console.log("phone token", token);

      // 유저 토큰 저장하기
      dispatch(userSlice.actions.setPhoneToken(token));

      return axios.post(`${Config.API_URL}/phonetoken`, { token });
    } catch (error) {
      console.error(error);
    }
  }

  getToken();
}, [dispatch]);
반응형
저작자표시 비영리 (새창열림)

'리액트 네이티브 (React Native)' 카테고리의 다른 글

리액트 네이티브 Failed to launch emulator 에러 해결하기  (0) 2022.11.25
리액트 네이티브 초기 프로젝트 생성 방법 (feat. Expo vs React Native CLI )  (0) 2022.11.09
리액트 네이티브 apk 파일 생성하기  (0) 2022.11.07
리액트 네이티브, 헤르메스(Hermes) 란?  (0) 2022.11.07
리액트 네이티브 코드 푸시(Code Push) 란, 그리고 코드 푸시 설정법  (2) 2022.11.07
    '리액트 네이티브 (React Native)' 카테고리의 다른 글
    • 리액트 네이티브 Failed to launch emulator 에러 해결하기
    • 리액트 네이티브 초기 프로젝트 생성 방법 (feat. Expo vs React Native CLI )
    • 리액트 네이티브 apk 파일 생성하기
    • 리액트 네이티브, 헤르메스(Hermes) 란?
    Jake Seo
    Jake Seo
    ✔ 잘 보셨다면 광고 한번 클릭해주시면 큰 힘이 됩니다. ✔ 댓글로 틀린 부분을 지적해주시면 기분 나빠하지 않고 수정합니다. ✔ 많은 퇴고를 거친 글이 좋은 글이 된다고 생각합니다. ✔ 간결하고 명료하게 사람들을 이해 시키는 것을 목표로 합니다.

    티스토리툴바