푸시 알림 연동
푸시 알림 권한 요청부터 FCM 토큰 발급, 로컬 알림 발송까지의 전체 플로우를 다룹니다.
개요
Appify SDK의 Notification 모듈을 통해 다음 세 가지 기능을 구현할 수 있습니다.
- 권한 확인: 사용자가 알림 권한을 허용했는지 확인합니다.
- FCM 토큰 발급: 서버 푸시 발송에 필요한 기기 토큰을 가져옵니다.
- 로컬 알림 발송: 서버 없이 기기에서 직접 알림을 표시합니다.
전체 플로우
1. 알림 권한 확인 및 요청
checkPermission()은 현재 알림 권한 상태를 확인합니다. 권한이 아직 결정되지 않은 경우 시스템 권한 요청 다이얼로그를 표시하고, 사용자가 허용하면 true를 반환합니다.
import { appify } from "@nolraunsoft/appify-sdk";
const isGranted = await appify.notification.checkPermission();
if (!isGranted) {
// 권한이 거부된 경우 알림 관련 기능을 비활성화합니다.
console.warn("알림 권한이 거부되었습니다.");
}
2. FCM 토큰 발급
권한이 허용된 이후 getToken()을 호출하면 Firebase Cloud Messaging(FCM) 토큰을 받을 수 있습니다. 이 토큰은 서버에서 특정 기기로 푸시 메시지를 보낼 때 사용합니다.
import { appify } from "@nolraunsoft/appify-sdk";
const token = await appify.notification.getToken();
console.log("FCM 토큰:", token);
3. 서버에 토큰 등록
발급받은 토큰을 서버에 전송하여 저장합니다. 이후 서버에서 해당 토큰으로 푸시 메시지를 발송합니다.
import { appify } from "@nolraunsoft/appify-sdk";
async function registerTokenToServer(userId: string): Promise<void> {
const token = await appify.notification.getToken();
await fetch("/api/push/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId, token }),
});
}
4. 로컬 알림 발송
sendLocalNotification()은 서버를 거치지 않고 기기에서 직접 알림을 표시합니다. 완료 알림, 타이머 알림 등 즉각적인 피드백이 필요한 상황에 적합합니다.
import { appify } from "@nolraunsoft/appify-sdk";
const success = await appify.notification.sendLocalNotification({
title: "주문이 완료되었습니다",
body: "상품이 3일 이내에 도착할 예정입니다.",
});
if (!success) {
console.warn("로컬 알림 발송에 실패했습니다.");
}
전체 초기화 예제
앱 시작 시 권한 확인, 토큰 발급, 서버 등록을 하나의 함수로 처리하는 패턴입니다.
import { appify } from "@nolraunsoft/appify-sdk";
async function initializePushNotification(userId: string): Promise<void> {
const isGranted = await appify.notification.checkPermission();
if (!isGranted) {
console.warn("알림 권한이 허용되지 않아 푸시 알림을 사용할 수 없습니다.");
return;
}
const token = await appify.notification.getToken();
await fetch("/api/push/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId, token }),
});
console.log("푸시 알림 초기화 완료");
}
React 환경에서는 초기화 후 한 번 호출합니다.
import { useEffect } from "react";
import { appify } from "@nolraunsoft/appify-sdk";
export function useInitPush(userId: string) {
useEffect(() => {
initializePushNotification(userId);
}, [userId]);
}
플랫폼별 참고사항
iOS
- APNs(Apple Push Notification service)를 Firebase가 중계하는 방식으로 동작합니다.
- Xcode 프로젝트에서 Push Notifications capability가 활성화되어 있어야 합니다.
- 시뮬레이터에서는
getToken()이 유효한 토큰을 반환하지 않습니다. 실기기에서 테스트하세요.
Android
- Android 13(API 33) 이상에서는
POST_NOTIFICATIONS권한이 필요합니다.checkPermission()호출 시 자동으로 권한 요청 다이얼로그가 표시됩니다. - Android 12 이하에서는 권한 요청 없이 알림이 기본 허용됩니다.
관련 API
메서드 전체 명세는 알림 모듈 레퍼런스를 참고하세요.