[Notifee] onBankgroundEvent() at quit/kill state

지원·2024년 5월 13일

!error

목록 보기
7/9

Do you have a screen named 'Chat'?
If you're trying to navigate to a screen in a nested navigator, see https://reactnavigation.org/docs/nesting-navigators#navigating-to-a-screen-in-a-nested-navigator.
This is a development-only warning and won't be shown in production.

문제

index.js에서 onBackgroundEvent()로 알림을 클릭했을 때 채팅 화면으로 이동하게 하고 있었는데, 포그라운드에서 받은 알림을 앱 종료 후에 클릭하면 앱이 로딩이 안된 상태에서 index.js가 실행되니까 navigate가 안되는 이슈 발생

원래 의도는 onBackgroundEvent()로 백그라운드 상태만 처리하고, getInitialNotification()으로 종료됐을 때를 처리하려고 했었음

// index.js
notifee.onBackgroundEvent(async ({
    type,
    detail
}) => {
    if (type === EventType.PRESS) {
        console.log('notifee back', detail);

        navigate('Chat', {
            id: id,
						...
        });
    }
    await notifee.cancelNotification(detail.notification.id);
});
// notificationHandler.js
const handleInitialNotification = async () => {
    const initialNotification = await notifee.getInitialNotification();

    if (initialNotification) {
        console.log('Notification caused application to open', initialNotification.notification);
        handleClickNotification(initialNotification.notification.data);

        await notifee.cancelNotification(initialNotification.notification.id);
    }
};

onBackgroundEvent()가 먼저 실행 -> getInitialNotification() 실행
워닝 수준의 에러라서 채팅창으로 잘 가긴 함.

해결

에러만 안뜨면 돼서 try/catch문을 쓰거나 할랬는데, 구글링을 해봐도 잘 모르겠어서 그냥 원래 의도대로 onBackgroundEvent()를 앱이 백그라운드 상태일 때만 실행되게 했음.

const handleAppStateChange = (next) => {
  	//현재 종료 또는 백그라운드 실행 상태, 다음 상태가 실행 중일 때
    if (appState.match(/inactive|background/) && next === 'active') {	
        console.log('App has gone to the foreground!');
    }
    if (appState.match(/active/) && next.match(/inactive|background/)) {
        console.log('App has gone to the background!');
        notifee.onBackgroundEvent(async ({
            type,
            detail
        }) => {
            if (type === EventType.PRESS) {
                console.log('notifee back', detail);

                navigate('Chat', {
                    id: id,
										...
                });
            }
            await notifee.cancelNotification(detail.notification.id);
        });
    }

    appState = next;
    console.log("Current state:", appState);
}

handleAppStateChange: AppState로 앱의 현재 상태를 받아와서 상태가 변경될 때마다 호출되는 함수

앱이 백그라운드로 전환되었을 때만 navigate하도록 변경

앱이 백그라운드일 때에만 onBackgroundEvent() 코드를 넣어놔서 종료했을 때 알림을 클릭하면 백그라운드 핸들러가 없다는 경고가 콘솔에 뜬다..

주의) navigate를 막는 거지 클릭 했을 때 해당 동작을 완전히 막는 것은 아님

지피티의 도움으로 해결함

0개의 댓글