import React, {useEffect, useState} from ‘react’;
import {Text, StyleSheet, View, Button, SafeAreaView, StatusBar,
useColorScheme, Alert, BackHandler} from ‘react-native’;
import {fcmService} from ‘./src/FCMService’;
import {localNotificationService} from ‘./src/LocalNotificationService’;
import AsyncStorage from ‘@react-native-community/async-storage’;
import MyWebView from ‘./component/MyWebView’;
export default function App() {
useEffect(() => {
fcmService.registerAppWithFCM();
fcmService.register(onRegister, onNotification, onOpenNotification);
localNotificationService.configure(onOpenNotification);
function onRegister(token) {
console.log('[App] onRegister : token :', token);
AsyncStorage.setItem('htoken', token)
}
function onNotification(notify) {
//console.log('[App] onNotification : notify :', notify);
const options = {
soundName: 'default',
playSound: true,
};
localNotificationService.showNotification(
0,
notify.title,
notify.body,
notify,
options,
);
}
function onOpenNotification(notify) {
//console.log('[App] onOpenNotification : notify :', notify);
alert('Open Notification : notify.body :' + notify.body);
}
return () => {
//console.log('[App] unRegister');
fcmService.unRegister();
localNotificationService.unregister();
};
}, []);
useEffect(() => {
const storage = async()=>{
let items = await AsyncStorage.getItem('htoken');
console.log('log',items)
}
storage()
}, []);
const isDarkMode = useColorScheme() === ‘dark’;
return (
<>
<StatusBar barStyle={isDarkMode ? ‘light-content’ : ‘dark-content’} />
<MyWebView
handleClose={(token)=>{
Alert.alert(‘앱 종료’, ‘앱을 종료하시겠습니까?’, [
{ text: ‘아니오’, onPress: () => null, },
{text: ‘예’, onPress: () => BackHandler.exitApp()},
]);
}}/>
</SafeAreaView>
</>
);
/*
return (
Push Test
<Button title=“Test” onPress={() => alert(“푸시”)} />
<Button
title=“Press”
onPress={() => localNotificationService.cancelAllLocalNotifications()}
/>
);
*/
}
const styles = StyleSheet.create({
root: {
flex: 1,
justifyContent: ‘center’
}, });
app.js 인데요
저 onregister 함수안에서 받아오는 token을 전연변수처럼 변수에 저장해서 다른곳에서 사용할수
있는 방법이 있을까요?
웹뷰에서 실행되는 페이지에 토큰을 전달해줘야 하는데 어떻게 해야 할지를 모르겠습니다.
asyncstorage를 이용하면 될까 했는데 getitem으로 가져오는것도 잘 안되고
웹뷰를 관리하는 페이지에서 source={{uri: “https://a.com/token=”+token}} 형태라도 테스트로 해보고 싶은데 저렇게 전달을 해줄수 있는 방법을 모르겠습니다.
알려주실수 있는분 계실까요?
토큰을 불러오는 fcmservice 는 아래처럼 되어있습니다. 저 토큰을 아무데서나 끌어내오고 싶은데
이쪽관련 지식이 없어 너무 힘드네요
import messaging from ‘@react-native-firebase/messaging’;
import {Platform} from ‘react-native’;
class FCMService {
register = (onRegister, onNotification, onOpenNotification) => {
this.checkPermission(onRegister);
this.createNotificationListeners(
onRegister,
onNotification,
onOpenNotification,
);
};
registerAppWithFCM = async () => {
if (Platform.OS === ‘ios’) {
// await messaging().registerDeviceForRemoteMessages();
await messaging().setAutoInitEnabled(true);
}
};
checkPermission = (onRegister) => {
messaging()
.hasPermission()
.then((enabled) => {
if (enabled) {
//User has permission
this.getToken(onRegister);
} else {
//User doesn’t have permission
this.requestPermission(onRegister);
}
})
.catch((error) => {
console.log(’[FCMService] Permission rejected ', error);
});
};
getToken = (onRegister) => {
messaging()
.getToken()
.then((fcmToken) => {
if (fcmToken) {
onRegister(fcmToken);
} else {
console.log(’[FCMService] User does not have a device token’);
}
})
.catch((error) => {
console.log(’[FCMService] getToken rejected’, error);
});
};
requestPermission = (onRegister) => {
messaging()
.requestPermission()
.then(() => {
this.getToken(onRegister);
})
.catch((error) => {
console.log(’[FCMService] Request Permission rejected’, error);
});
};
deleteToken = () => {
console.log(’[FCMService] deleteToken’);
messaging()
.deleteToken()
.catch((error) => {
console.log(’[FCMService] Delete token error’, error);
});
};
createNotificationListeners = (
onRegister,
onNotification,
onOpenNotification,
) => {
//실행중이지만 현재화면은 다른 앱이 실행중이거나 아무것도 실행하지않을때
messaging().onNotificationOpenedApp((remoteMessage) => {
console.log(
‘[FCMService] onNotificationOpenApp Notification caused app to open from background’,
remoteMessage,
);
if (remoteMessage) {
const notification = remoteMessage.notification;
onOpenNotification(notification);
//this.removeDeliveredNotification(Notification.NotificationId)
} else {
console.log(‘background notification error’, error);
}
alert(remoteMessage.body);
});
//Check whether an initial notification is available
//앱이 실행중이 아닐때
messaging()
.getInitialNotification()
.then((remoteMessage) => {
console.log(
'[FCMService] getInitialNotification casued app to open from quit state : fcmremoteMessage :',
remoteMessage,
);
if (remoteMessage) {
const notification = remoteMessage.notification;
onOpenNotification(notification);
//this.removeDeliveredNotification(notification.notificationId)
} else {
console.log('quit state notification error : ', error);
}
});
//실행중이고 현재 화면일때
this.messageListener = messaging().onMessage(async (remoteMessage) => {
console.log('[FCMService] A new FCM message arrived', remoteMessage);
if (remoteMessage) {
let notification = null;
if (Platform.OS === 'ios') {
notification = remoteMessage.data.notification;
} else {
notification = remoteMessage.notification;
}
onNotification(notification);
}
});
//Triggerd when have new token
messaging().onTokenRefresh((fcmToken) => {
console.log('[FCMService] New token refresh :', fcmToken);
onRegister(fcmToken);
});
};
unRegister = () => {
this.messageListener();
};
}
export const fcmService = new FCMService();