csa-react-60/App.js

220 lines
5.9 KiB
JavaScript

/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
import React, { Component } from 'react'
import { StatusBar, StyleSheet, Text, TouchableOpacity, Platform } from 'react-native'
import MainNav from './src/navigation/MainNav'
import messaging from "@react-native-firebase/messaging"
import { persistor, store } from './src/redux/store'
import { Provider } from 'react-redux'
import { registerDevice } from './src/api/UserApi'
import { appSetDevice, appSetPushToken } from './src/redux/app/action'
import { setLanguage, setToken } from 'src/api/api'
import { PersistGate } from 'redux-persist/integration/react'
import Toast from 'react-native-toast-message'
import SplashScreen from 'react-native-splash-screen'
import { setBaseUrlByServerMode } from './src/api/api'
import { Settings } from 'react-native-fbsdk-next';
import notifee, { AndroidImportance } from '@notifee/react-native';
Text.defaultProps = Text.defaultProps || {}
Text.defaultProps.allowFontScaling = false
if (TouchableOpacity.defaultProps == null) TouchableOpacity.defaultProps = {}
TouchableOpacity.defaultProps.activeOpacity = 0.7
// setApiStore(store)
class App extends Component {
constructor(props) {
super(props)
this._setDataFromInitState = this._setDataFromInitState.bind(this)
this.unsubscribe = null;
}
componentDidMount = async () => {
SplashScreen.hide()
Settings.initializeSDK();
await this.requestUserPermission();
this.unsubscribe = messaging().onMessage(async remoteMessage => {
console.log('A new FCM message arrived!', remoteMessage);
await this.onDisplayNotification(remoteMessage);
});
try {
const token = await messaging().getToken();
console.log('Current FCM Token:', token);
console.log('Token length:', token ? token.length : 0);
const authStatus = await messaging().requestPermission();
console.log('Permission status:', authStatus);
} catch (error) {
console.log('Error getting FCM token:', error);
}
}
componentWillUnmount() {
if (this.unsubscribe) {
this.unsubscribe();
}
}
requestUserPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
}
};
onDisplayNotification = async (remoteMessage) => {
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
importance: AndroidImportance.HIGH,
});
await notifee.displayNotification({
title: remoteMessage.notification.title,
body: remoteMessage.notification.body,
android: {
channelId,
smallIcon: 'ic_launcher'
},
ios: {
foregroundPresentationOptions: {
badge: true,
sound: true,
banner: true,
},
},
});
};
initNotification = async () => {
try {
await this.setPermission()
if (Platform.OS === 'ios') {
let apnsToken = await messaging().getAPNSToken();
let retry = 0;
while (!apnsToken && retry < 10) {
console.log('Waiting for APNs token...');
await new Promise(resolve => setTimeout(resolve, 1000));
apnsToken = await messaging().getAPNSToken();
retry++;
}
console.log('APNs Token:', apnsToken);
if (!apnsToken) {
console.log('Failed to get APNs token after retries');
// Decide if we want to return here or try anyway.
// Usually if APNs is missing, getToken will fail.
}
}
// ใช้ getToken() แทน getAPNSToken()
const fcmToken = await messaging().getToken();
console.log('FCM Token:', fcmToken);
if (fcmToken) {
store.dispatch(appSetPushToken(fcmToken))
const resultSendDevice = await registerDevice(fcmToken)
console.log('register_device result =>', resultSendDevice)
if (resultSendDevice.ok && resultSendDevice.data.success) {
store.dispatch(appSetDevice(resultSendDevice.data.device))
}
}
// เพิ่ม notification listeners
this.setupNotificationListeners();
} catch (error) {
console.log('initNotification error:', error);
}
}
setPermission = async () => {
try {
await messaging().registerDeviceForRemoteMessages();
const authStatus = await messaging().requestPermission();
const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (!enabled) {
await messaging().requestPermission()
}
} catch (error) {
console.log('error', error)
}
}
_setDataFromInitState() {
const appState = store.getState().app
let device = appState.device
setBaseUrlByServerMode(appState.server_mode)
if (appState.token) {
setToken(appState.token)
}
if (appState.lang) {
setLanguage(appState.lang)
}
if (!device) {
this.initNotification()
} else {
this.setPermission()
this.setupNotificationListeners()
}
console.log('app state', appState, device)
}
render() {
return (
<Provider store={store}>
<PersistGate persistor={persistor} loading={null} onBeforeLift={this._setDataFromInitState}>
<StatusBar barStyle="light-content" />
<MainNav />
</PersistGate>
<Toast />
</Provider>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
})
export default App