fix ios push notification registration

This commit is contained in:
kanyanat 2025-12-01 14:40:13 +07:00
parent 86eec87b8c
commit 601bd7fb56
2 changed files with 166 additions and 162 deletions

13
App.js
View File

@ -31,7 +31,7 @@ TouchableOpacity.defaultProps.activeOpacity = 0.7
// setApiStore(store) // setApiStore(store)
class App extends Component { class App extends Component {
constructor (props) { constructor(props) {
super(props) super(props)
this._setDataFromInitState = this._setDataFromInitState.bind(this) this._setDataFromInitState = this._setDataFromInitState.bind(this)
} }
@ -120,7 +120,7 @@ class App extends Component {
} }
} }
_setDataFromInitState () { _setDataFromInitState() {
const appState = store.getState().app const appState = store.getState().app
let device = appState.device let device = appState.device
@ -135,19 +135,22 @@ class App extends Component {
if (!device) { if (!device) {
this.initNotification() this.initNotification()
} else {
this.setPermission()
this.setupNotificationListeners()
} }
console.log('app state', appState, device) console.log('app state', appState, device)
} }
render () { render() {
return ( return (
<Provider store={store}> <Provider store={store}>
<PersistGate persistor={persistor} loading={null} onBeforeLift={this._setDataFromInitState}> <PersistGate persistor={persistor} loading={null} onBeforeLift={this._setDataFromInitState}>
<StatusBar barStyle="light-content"/> <StatusBar barStyle="light-content" />
<MainNav/> <MainNav />
</PersistGate> </PersistGate>
<Toast /> <Toast />
</Provider> </Provider>

View File

@ -1,17 +1,17 @@
import React, {Component, useCallback} from 'react'; import React, { Component, useCallback } from 'react';
import { TouchableOpacity, View, Alert, ScrollView, SafeAreaView, KeyboardAvoidingView, Platform } from 'react-native' import { TouchableOpacity, View, Alert, ScrollView, SafeAreaView, KeyboardAvoidingView, Platform } from 'react-native'
import Image from 'react-native-fast-image' import Image from 'react-native-fast-image'
import GetWidthHeightDevice from '../../components/GetWidthHeightDevice' import GetWidthHeightDevice from '../../components/GetWidthHeightDevice'
import { CustomButton } from '../../components/CustomButton' import { CustomButton } from '../../components/CustomButton'
import { CustomInput } from '../../components/CustomInput' import { CustomInput } from '../../components/CustomInput'
import {login, payment} from '../../api/UserApi' import { login, payment } from '../../api/UserApi'
import { setToken } from '../../api/api' import { setToken } from '../../api/api'
import { BackgroundImage } from '../../components/BackgroundImage' import { BackgroundImage } from '../../components/BackgroundImage'
import LinearGradient from 'react-native-linear-gradient' import LinearGradient from 'react-native-linear-gradient'
import Text from '../../components/Text' import Text from '../../components/Text'
import { bindActionCreators } from 'redux' import { bindActionCreators } from 'redux'
import {appSetDevice, appSetPushToken, appSetToken, appSetUser} from '../../redux/app/action' import { appSetDevice, appSetPushToken, appSetToken, appSetUser } from '../../redux/app/action'
import {connect} from 'react-redux' import { connect } from 'react-redux'
import IndicatorLoading from '../../components/IndicatorLoading'; import IndicatorLoading from '../../components/IndicatorLoading';
import { locale, t } from '../../utils/i18n' import { locale, t } from '../../utils/i18n'
import moment from "moment"; import moment from "moment";
@ -27,8 +27,8 @@ class LoginScreen extends Component {
password: null, password: null,
payment: [], payment: [],
sum_payment: [], sum_payment: [],
all_payment : [], all_payment: [],
room_number_array : [], room_number_array: [],
} }
this._login = this._login.bind(this) this._login = this._login.bind(this)
} }
@ -39,172 +39,173 @@ class LoginScreen extends Component {
} }
async _login () { async _login() {
this.setState({ this.setState({
isLoading: true isLoading: true
}, async () => { }, async () => {
if (this.state.username && this.state.password) { if (this.state.username && this.state.password) {
var regex = /^\d+$/; var regex = /^\d+$/;
let fcmToken = null; let fcmToken = null;
if (regex.test(this.state.username) === true) { if (regex.test(this.state.username) === true) {
console.log('true') console.log('true')
try { try {
const authStatus = await messaging().requestPermission({ const authStatus = await messaging().requestPermission({
alert: true, alert: true,
sound: true, sound: true,
badge: true, badge: true,
}); });
console.log('authStatus >>> ', authStatus) console.log('authStatus >>> ', authStatus)
const enabled = const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL; authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) { if (enabled) {
console.log('Notification permission granted.'); console.log('Notification permission granted.');
fcmToken = await messaging().getToken(); await messaging().registerDeviceForRemoteMessages();
console.log('fcmToken >>>> ', fcmToken) fcmToken = await messaging().getToken();
} else { console.log('fcmToken >>>> ', fcmToken)
console.log('Notification permission denied.');
}
} catch (error) {
console.error('Failed to request notification permission:', error);
}
// const fcmToken = await messaging().getAPNSToken()
console.log('await messaging().getAPNSToken() <<<<<< ', fcmToken)
let params = {
// mobile: this.state.username,
username: this.state.username,
password: this.state.password,
fcm_token: fcmToken
}
console.log('params >> ', params)
// console.log('fcmToken >>>>>>>>>>>>>>>>>>>>>>>>> ', fcmToken)
this.setState({isLoading:true})
login(params)
.then((res) => {
if (res.ok) {
if (res.data.access_token) {
setToken(res.data.access_token)
this.props.appSetToken(res.data.access_token)
this.props.navigation.navigate('HomeScreen',{isLogin:true})
let user_data = res.data.user;
this.props.appSetUser(user_data)
}
this.setState({ isLoading: false })
} else { } else {
this.setState({ console.log('Notification permission denied.');
isLoading: false
}, () => {
Alert.alert(null, t('credential_invalid'))
})
} }
}) } catch (error) {
console.error('Failed to request notification permission:', error);
}
// const fcmToken = await messaging().getAPNSToken()
console.log('await messaging().getAPNSToken() <<<<<< ', fcmToken)
let params = {
// mobile: this.state.username,
username: this.state.username,
password: this.state.password,
fcm_token: fcmToken
}
console.log('params >> ', params)
// console.log('fcmToken >>>>>>>>>>>>>>>>>>>>>>>>> ', fcmToken)
this.setState({ isLoading: true })
login(params)
.then((res) => {
if (res.ok) {
if (res.data.access_token) {
setToken(res.data.access_token)
this.props.appSetToken(res.data.access_token)
this.props.navigation.navigate('HomeScreen', { isLogin: true })
let user_data = res.data.user;
this.props.appSetUser(user_data)
}
this.setState({ isLoading: false })
} else {
this.setState({
isLoading: false
}, () => {
Alert.alert(null, t('credential_invalid'))
})
}
})
} else {
Alert.alert(null, t('phone_format_invalid'))
this.setState({ isLoading: false })
}
} else { } else {
Alert.alert(null, t('phone_format_invalid')) Alert.alert(null, t('required_field'))
this.setState({ isLoading: false }) this.setState({ isLoading: false })
} }
} else {
Alert.alert(null, t('required_field'))
this.setState({ isLoading: false })
}
}) })
}; };
render() { render() {
return ( return (
<SafeAreaView style={{flex: 1}}> <SafeAreaView style={{ flex: 1 }}>
<LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{ <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
flex: 1, flex: 1,
width: null, width: null,
height: null, height: null,
resizeMode: 'cover' resizeMode: 'cover'
}}> }}>
<BackgroundImage> <BackgroundImage>
<KeyboardAvoidingView style={{flex:1}} keyboardVerticalOffset={Platform.OS == 'ios' ? 70 : 0} behavior={Platform.OS == 'ios' ? "padding" : ""} enabled> <KeyboardAvoidingView style={{ flex: 1 }} keyboardVerticalOffset={Platform.OS == 'ios' ? 70 : 0} behavior={Platform.OS == 'ios' ? "padding" : ""} enabled>
<ScrollView showsVerticalScrollIndicator={true} style={{ flex: 1}}> <ScrollView showsVerticalScrollIndicator={true} style={{ flex: 1 }}>
<View style={styles.container}> <View style={styles.container}>
<View style={styles.logo}> <View style={styles.logo}>
{/*<Text> Logo </Text>*/} {/*<Text> Logo </Text>*/}
<View style={{ <View style={{
flexGrow: 1, alignItems: 'center', justifyContent: 'center', paddingVertical: 10, flexGrow: 1, alignItems: 'center', justifyContent: 'center', paddingVertical: 10,
}}> }}>
<Image <Image
style={{ width: 170, height: 170 }} style={{ width: 170, height: 170 }}
source={require('../../../assets/images/logo_white_border.png')} source={require('../../../assets/images/logo_white_border.png')}
/> />
<View style={{ marginTop: 5, alignItems: 'center', }}> <View style={{ marginTop: 5, alignItems: 'center', }}>
<Text style={{ fontSize: 28, color: '#FFF', fontFamily: 'Prompt-Medium' }}>เจรญสนธาน</Text> <Text style={{ fontSize: 28, color: '#FFF', fontFamily: 'Prompt-Medium' }}>เจรญสนธาน</Text>
<Text style={{ fontSize: 18, color: '#FFF' }}>({t('room_for_rent')})</Text> <Text style={{ fontSize: 18, color: '#FFF' }}>({t('room_for_rent')})</Text>
</View>
</View>
</View> </View>
</View> <View style={styles.form}>
</View> <View style={styles.row}>
<View style={styles.form}> <CustomInput
<View style={styles.row}> maxLength={13}
<CustomInput keyboardType="numeric"
maxLength={13} onChangeText={(e) => {
keyboardType="numeric" this.setState({
onChangeText={(e) => { username: e
this.setState({ })
username: e }}
}) onEndEditing={(e) => {
}} this.setState({
onEndEditing={(e) => { username: e.nativeEvent.text
this.setState({ })
username: e.nativeEvent.text }}
}) inputTextAlign={'left'}
}} iconName={'ic_user'}
inputTextAlign={'left'} placeholder={t('phone')}
iconName={'ic_user'} placeholderTextColor={'#FFFFFF40'}
placeholder={t('phone')} style={styles.form_input} />
placeholderTextColor={'#FFFFFF40'} </View>
style={styles.form_input} /> <View style={styles.row}>
</View> <CustomInput
<View style={styles.row}>
<CustomInput
inputTextAlign={'left'} inputTextAlign={'left'}
secureTextEntry={true} secureTextEntry={true}
iconName={'ic_key'} iconName={'ic_key'}
placeholder={t('password')} placeholder={t('password')}
placeholderTextColor={'#FFFFFF40'} placeholderTextColor={'#FFFFFF40'}
onChangeText={(e) => { onChangeText={(e) => {
this.setState({ this.setState({
password: e password: e
}) })
}} }}
onEndEditing={(e) => { onEndEditing={(e) => {
this.setState({ this.setState({
password: e.nativeEvent.text password: e.nativeEvent.text
}) })
}} }}
style={styles.form_input} /> style={styles.form_input} />
</View> </View>
<View style={{flex: 1, marginBottom: 10}}> <View style={{ flex: 1, marginBottom: 10 }}>
<TouchableOpacity onPress={() => this.props.navigation.navigate('ForgetPassword')}> <TouchableOpacity onPress={() => this.props.navigation.navigate('ForgetPassword')}>
<Text style={{color: '#FFF', fontSize: 15, textAlign: 'right'}}>{t('forget_password')}?</Text> <Text style={{ color: '#FFF', fontSize: 15, textAlign: 'right' }}>{t('forget_password')}?</Text>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
<View style={[styles.row, { marginTop: 15 }]}> <View style={[styles.row, { marginTop: 15 }]}>
<CustomButton <CustomButton
colorText={'#2470A1'} colorText={'#2470A1'}
weightText={'Prompt-Bold'} weightText={'Prompt-Bold'}
title={t('login')} title={t('login')}
sizeText={16} sizeText={16}
style={[styles.btn_login]} style={[styles.btn_login]}
onPress={this._login} onPress={this._login}
//onPress={() => { this.props.navigation.navigate('HomeScreen') }} //onPress={() => { this.props.navigation.navigate('HomeScreen') }}
/> />
</View> </View>
{/* <View style={{marginTop:10}}> {/* <View style={{marginTop:10}}>
<View style={[styles.row, { flex: 1, flexDirection: locale() == 'my' ? 'column' : 'row', alignItems: 'center', textAlign: 'center', justifyContent: 'center' }]}> <View style={[styles.row, { flex: 1, flexDirection: locale() == 'my' ? 'column' : 'row', alignItems: 'center', textAlign: 'center', justifyContent: 'center' }]}>
<Text style={{ color: '#FFF', fontSize: 15}}> {t('not_a_member')} </Text> <Text style={{ color: '#FFF', fontSize: 15}}> {t('not_a_member')} </Text>
<TouchableOpacity onPress={() => { this.props.navigation.navigate('Register') }}> <TouchableOpacity onPress={() => { this.props.navigation.navigate('Register') }}>
@ -212,13 +213,13 @@ class LoginScreen extends Component {
</TouchableOpacity> </TouchableOpacity>
</View> </View>
</View> */} </View> */}
</View> </View>
</View> </View>
</ScrollView> </ScrollView>
</KeyboardAvoidingView> </KeyboardAvoidingView>
</BackgroundImage> </BackgroundImage>
<IndicatorLoading loadingVisible={this.state.isLoading}/> <IndicatorLoading loadingVisible={this.state.isLoading} />
</LinearGradient> </LinearGradient>
</SafeAreaView> </SafeAreaView>
) )
} }