- 기존 트리거 생성과 동일한 createTriggerNotification() 메서드를 사용합니다. 단, 해당 메서드의 파라미터로 id 값을 이전에 생성된 triggerId로 사용하여 트리거 알람을 업데이트합니다.
1. Date.now() 함수를 통해서 현재 시간을 가져와서 현재 시간 기준으로 이후 시간으로 알람을 정합니다. - 해당 부분에 변경하려는 시간을 추가하였습니다.
2. createChannel() 메서드를 통해 채널을 생성합니다. TimestampTrigger를 통해 지정한 시간을 객체로 만듭니다.
- createTriggerNotification() 메서드를 통해 지정한 알람시간에 메시지를 받습니다. 처리 이후 트리거 아이디를 반환받습니다. - 해당 부분에서 일반 Notification() 생성의 경우 id 속성이 포함되지 않았지만, 해당 업데이트의 경우는 id를 기존에 있는 트리거 아이디로 가져와서 이를 수정합니다. - 해당 id가 존재하지 않으면 Notification이 추가됩니다.
/**
* 트리거 아이디 값을 기반으로 트리거 알람을 변경합니다.
*/
updateTriggerAlarm: async () => {
console.log("[+] 특정 트리거를 수정합니다.")
console.log("[+] 변경하려는 triggerId :: ", triggerId)
// 트리거 알람 시간 설정
const date = new Date(Date.now());
date.setMinutes(date.getMinutes() + 1);
date.setSeconds(0);
// 채널 생성
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
});
console.log("[+] 채널이 생성되었습니다. :", channelId)
// 트리거 생성
const trigger: TimestampTrigger = {
type: TriggerType.TIMESTAMP,
timestamp: date.getTime(), // 현재 시간 기준 1분뒤 알람 설정
};
// 트리거 생성 후 지정한 시간에 푸시 메시지 알람. : 결과 값으로 트리거 아이디를 반환받습니다.
const _triggerId = await notifee.createTriggerNotification(
{
id: triggerId, // 해당 값을 기반으로 트리거를 변경합니다.
title: '미팅이 1분뒤에 있습니다(변경!)',
body: `Today at ${cvtDateHandler.getHourMin(date)}`,
android: {
channelId: channelId,
},
},
trigger,
);
console.log("triggerId ::" + _triggerId)
}
4) Notifee Trigger 활용 종합
💡 Notifee Trigger 활용 종합
- 위에서 활용한 내용을 공통되는 부분을 정리하여 최종 정리한 소스코드입니다.
import { useEffect, useState } from "react";
import { Text, TouchableHighlight, View } from "react-native"
import messaging from '@react-native-firebase/messaging';
import notifee, { IntervalTrigger, RepeatFrequency, TimestampTrigger, TimeUnit, TriggerType } from '@notifee/react-native';
const NotificationScreen = () => {
const [triggerId, setTriggerId] = useState("");
const [channelIdInfo, setChannelIdInfo] = useState<string>("");
const [notificationId, setNotificationId] = useState("");
useEffect(() => {
initSetting();
const subscribeForeground = messaging().onMessage(onMessageReceived);
return () => {
subscribeForeground;
}
}, []);
/**
* 최초 채널을 생성하여 state에 저장합니다.
*/
const initSetting = async () => {
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
});
console.log("[+] 채널이 생성되었습니다. :", channelId)
setChannelIdInfo(channelId);
}
/**
* FCM 메시지 수신 리스너를 등록합니다. (Foreground, Background 상태)
* @param message
*/
const onMessageReceived = async (message) => {
const { title, body } = message.notification!;
const messageId = message.messageId;
setNotificationId(messageId);
console.log(message)
// 디바이스에 알림을 표시합니다.
await notifee.displayNotification({
title: title,
body: body,
android: {
channelId: channelIdInfo,
smallIcon: 'ic_launcher',
},
});
}
/**
* 트리거 알람을 통한 처리 핸들러
*/
const triggerAlarmHandler = (() => {
return {
/**
* 트리거 알람 생성(특정 시간)합니다.
*/
createTiggerAlarm: async () => {
console.log("[+] 1분 뒤 알람을 생성하였습니다.")
// 트리거 알람 시간 설정
const date = new Date(Date.now());
date.setMinutes(date.getMinutes() + 1);
date.setSeconds(0);
// 트리거 생성
const trigger: TimestampTrigger = {
type: TriggerType.TIMESTAMP,
timestamp: date.getTime(), // 현재 시간 기준 1분뒤 알람 설정
};
// 트리거 생성 후 지정한 시간에 푸시 메시지 알람. : 결과 값으로 트리거 아이디를 반환받습니다.
const _triggerId = await notifee.createTriggerNotification(
{
title: '미팅이 1분뒤에 있습니다',
body: `Today at ${cvtDateHandler.getHourMin(date)}`,
android: {
channelId: channelIdInfo,
},
},
trigger,
);
setTriggerId(_triggerId)
console.log("생성된 triggerId ::" + _triggerId)
},
/**
* 일정 시간 반복 트리거 알림을 생성합니다.
*/
createRepeatTiggerAlarm: async () => {
console.log("[+] 매일 오후 5시의 알람을 생성하였습니다.")
const date = new Date(Date.now());
date.setHours(17)
date.setMinutes(0);
date.setSeconds(0);
const trigger: TimestampTrigger = {
type: TriggerType.TIMESTAMP,
timestamp: date.getTime(),
repeatFrequency: RepeatFrequency.DAILY,
};
const _triggerId = await notifee.createTriggerNotification(
{
title: '매일 17:00에 미팅이 있습니다.',
body: '주간보고 미팅',
android: {
channelId: channelIdInfo,
},
},
trigger,
);
setTriggerId(_triggerId)
console.log("생성된 triggerId ::" + _triggerId)
},
/**
* 현재 시간 기준 일정 기간(시간, 분, 초) 반복 트리거 알람을 생성합니다.
*/
createIntervalTriggerAlarm: async () => {
console.log("[+] 현재 시간 기준 30분 마다 알람을 생성하였습니다.")
const trigger: IntervalTrigger = {
type: TriggerType.INTERVAL,
interval: 1,
timeUnit: TimeUnit.MINUTES
};
const triggerId = await notifee.createTriggerNotification(
{
title: '30분 마다 물 마실 시간입니다.',
body: '건강을 위해 30분 마다 물을 마셔야합니다.',
android: {
channelId: channelIdInfo,
},
},
trigger,
);
console.log("triggerId ::" + triggerId)
},
/**
* 트리거의 아이디 또는 Notification 정보 목록을 조회합니다.
*/
searchTriggerAlram: async () => {
console.log("[+] 보류 중인 트리거 아이디 혹은 알람 정보를 조회합니다.")
const triggerIds = await notifee.getTriggerNotificationIds();
console.log("triggerIds :: ", triggerIds);
const notifications = await notifee.getTriggerNotifications();
console.log("notifications :: ", notifications)
},
/**
* 트리거 아이디를 기반으로 트리거 알람을 취소합니다.
*/
cancleTriggerAlarm: async () => {
console.log("[+] 단건의 트리거를 취소합니다.")
await notifee.cancelNotification("Rq5PfQ1e1VkV6wnwQMW0");
},
/**
* 현재 디바이스 추가된 트리거 알람을 모두 제거합니다.
*/
cancleAllTriggerAlarm: async () => {
console.log("[+] 모든 트리거 알람을 취소합니다.")
// 모든 트리거 아이디를 가져옵니다.
const triggerIds = await notifee.getTriggerNotificationIds();
console.log("triggerIds :: ", triggerIds);
// 모든 트리거 알람을 제거합니다.
await notifee.cancelAllNotifications(triggerIds);
},
/**
* 트리거 아이디 값을 기반으로 트리거 알람을 변경합니다.
*/
updateTriggerAlarm: async () => {
console.log("[+] 특정 트리거를 수정합니다.")
console.log("[+] 변경하려는 triggerId :: ", triggerId)
// 트리거 알람 시간 설정
const date = new Date(Date.now());
date.setMinutes(date.getMinutes() + 1);
date.setSeconds(0);
// 트리거 생성
const trigger: TimestampTrigger = {
type: TriggerType.TIMESTAMP,
timestamp: date.getTime(), // 현재 시간 기준 1분뒤 알람 설정
};
// 트리거 생성 후 지정한 시간에 푸시 메시지 알람. : 결과 값으로 트리거 아이디를 반환받습니다.
const _triggerId = await notifee.createTriggerNotification(
{
id: triggerId, // 해당 값을 기반으로 트리거를 변경합니다.
title: '미팅이 1분뒤에 있습니다(변경!)',
body: `Today at ${cvtDateHandler.getHourMin(date)}`,
android: {
channelId: channelIdInfo,
},
},
trigger,
);
console.log("triggerId ::" + _triggerId)
}
}
})();
/**
* DATE 타입을 입맛에 맞게 변경하는 Handler
*/
const cvtDateHandler = (() => {
return {
getDate: (date: Date) => {
const hours = date.getHours();
const minutes = "0" + date.getMinutes();
const seconds = "0" + date.getSeconds();
return hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
},
getHourMin: (date: Date) => {
const hours = date.getHours();
const minutes = date.getMinutes();
return `${hours}시 ${minutes}분`
}
}
})();
return (
<>
<View style={{ marginBottom: 30 }}></View>
<View style={{ margin: 20 }}>
<TouchableHighlight onPress={triggerAlarmHandler.createTiggerAlarm} style={{ borderWidth: 1, borderColor: "black" }}>
<Text>트리거 알람 만들기 </Text>
</TouchableHighlight>
</View>
<View style={{ margin: 20 }}>
<TouchableHighlight onPress={triggerAlarmHandler.createRepeatTiggerAlarm} style={{ borderWidth: 1, borderColor: "black" }}>
<Text>특정 시간 반복 트리거 알람 만들기 </Text>
</TouchableHighlight>
</View>
<View style={{ margin: 20 }}>
<TouchableHighlight onPress={triggerAlarmHandler.createIntervalTriggerAlarm} style={{ borderWidth: 1, borderColor: "black" }}>
<Text>특정 기간 반복 트리거 알람 만들기 </Text>
</TouchableHighlight>
</View>
<View style={{ margin: 20 }}>
<TouchableHighlight onPress={triggerAlarmHandler.searchTriggerAlram} style={{ borderWidth: 1, borderColor: "black" }}>
<Text>현재 알람 목록 </Text>
</TouchableHighlight>
</View>
<View style={{ margin: 20 }}>
<TouchableHighlight onPress={triggerAlarmHandler.cancleAllTriggerAlarm} style={{ borderWidth: 1, borderColor: "black" }}>
<Text>단건 알람 삭제</Text>
</TouchableHighlight>
</View>
<View style={{ margin: 20 }}>
<TouchableHighlight onPress={triggerAlarmHandler.updateTriggerAlarm} style={{ borderWidth: 1, borderColor: "black" }}>
<Text>트리거 알람 변경하기 </Text>
</TouchableHighlight>
</View>
</>
)
}
export default NotificationScreen