React 프로젝트에서 Capacitor 사용하기 마지막 시리즈, FCM 알림 설정을 해보겠다.
우리 서비스에서 Background 위치 기반으로 알림을 보낸 과정을 설명하자면,
따라서 프론트에서는 1. Background 위치를 서버에 전송하고, 2. 사용자 기기에 도달한 알림으로 관련 기능 구현했다.
오늘은 두 번째인 도달한 알림을 처리한 방법을 위주로 포스팅해보겠다.
FCM 페이지에서 설정을 마치면 생성되는 google-services.json
파일을 app/src
경로에 넣어준다.
> pnpm add @capacitor/push-notification
먼저 @capacitor/push-notification
package를 추가한다.
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/push_icon_name" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/colorAccent" />
다음은 푸시 알림 아이콘 관련 설정이다.
AndroidManifest.xml 파일의 application 태그 안에 두 가지 태그를 추가해준다.
android:resource=
여기에 내가 설정하고 싶은 아이콘, 색상 경로를 넣어주면 된다.
이제 capacitor.config.ts
파일에 아래 코드를 넣어준다.
import type { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
// ... other config
plugins: {
PushNotifications: {
presentationOptions: ['badge', 'sound', 'alert'],
},
},
};
export default config;
CapacitorPush Notification API 문서를 보면, pushNotificationActionPerformed
이벤트를 등록하면 알림이 클릭되었을 때 실행할 action을 설정할 수 있다.
import { PushNotifications } from '@capacitor/push-notifications';
import { postToken } from '@/api/notification';
import { NotificationData } from '@/types/notification';
import { NOTIFICATION_DATA_KEY } from '@/constants/notification';
export const initFCMListener = async () => {
// 권한 체크
let permStatus = await PushNotifications.checkPermissions();
if (permStatus.receive === 'prompt') {
permStatus = await PushNotifications.requestPermissions();
}
if (permStatus.receive === 'granted') {
await PushNotifications.register();
await PushNotifications.addListener('registration', async (token) => {
postToken(token.value);
});
await PushNotifications.addListener('registration', (tkn) => {
console.log(`Registration token: ${tkn.value}`);
});
await PushNotifications.addListener('registrationError', (err) => {
console.log(`Registration error: ${err.error}`);
});
// notification을 클릭했을 때 실행되는 listener
await PushNotifications.addListener('pushNotificationActionPerformed', async (notification) => {
// ✅ do something...
} else {
console.log('User denied permissions!');
}
};
나는 이벤트 리스너 안에서 알림 읽음 처리와 redirect를 해줬다.
그런데 여기서는 리액트 훅을 사용할 수 없어서 관련 정보를 sessionStorage에 저장하고 window.location.href = '/경로'
로 페이지를 이동시켰다.
알림 클릭 순간 표시할 도착지 위경도를 저장한거라 sessionStorage를 써도 문제는 없었지만 다른 방법은 없었을까 아직도 궁금 . . . 😢
개발 당시에는 막막하고 어려운 기능 구현이었는데
이렇게 회고 겸 포스팅을 하니까 정리가 되면서 좋다!
그럼 읽어주셔서 감사하고, 피드백은 언제나 환영합니다.😊