update get APNS token for ios platform

This commit is contained in:
kanyanat 2025-12-02 13:57:46 +07:00
parent 601bd7fb56
commit d24c733897
3 changed files with 129 additions and 84 deletions

20
App.js
View File

@ -7,7 +7,7 @@
*/ */
import React, { Component } from 'react' import React, { Component } from 'react'
import { StatusBar, StyleSheet, Text, TouchableOpacity } from 'react-native' import { StatusBar, StyleSheet, Text, TouchableOpacity, Platform } from 'react-native'
import MainNav from './src/navigation/MainNav' import MainNav from './src/navigation/MainNav'
import messaging from "@react-native-firebase/messaging" import messaging from "@react-native-firebase/messaging"
import { persistor, store } from './src/redux/store' import { persistor, store } from './src/redux/store'
@ -86,6 +86,24 @@ class App extends Component {
try { try {
await this.setPermission() 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() // ใช้ getToken() แทน getAPNSToken()
const fcmToken = await messaging().getToken(); const fcmToken = await messaging().getToken();
console.log('FCM Token:', fcmToken); console.log('FCM Token:', fcmToken);

View File

@ -64,6 +64,19 @@ class LoginScreen extends Component {
if (enabled) { if (enabled) {
console.log('Notification permission granted.'); console.log('Notification permission granted.');
await messaging().registerDeviceForRemoteMessages(); await messaging().registerDeviceForRemoteMessages();
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);
}
fcmToken = await messaging().getToken(); fcmToken = await messaging().getToken();
console.log('fcmToken >>>> ', fcmToken) console.log('fcmToken >>>> ', fcmToken)
} else { } else {

View File

@ -1,13 +1,13 @@
import React, { Component } from 'react' import React, { Component } from 'react'
import { ScrollView, TouchableOpacity, View, Alert } from 'react-native' import { ScrollView, TouchableOpacity, View, Alert, Platform } from 'react-native'
import Image from 'react-native-fast-image' import Image from 'react-native-fast-image'
import { CustomStepIndicator } from '../../components/StepIndicator' import { CustomStepIndicator } from '../../components/StepIndicator'
import GetWidthHeightDevice from '../../components/GetWidthHeightDevice' import GetWidthHeightDevice from '../../components/GetWidthHeightDevice'
import { CustomButton } from '../../components/CustomButton' import { CustomButton } from '../../components/CustomButton'
import { connect } from 'react-redux' import { connect } from 'react-redux'
import {checkPaymentMeter, register, registerDevice, testConnect} from '../../api/UserApi' import { checkPaymentMeter, register, registerDevice, testConnect } from '../../api/UserApi'
import { bindActionCreators } from 'redux' import { bindActionCreators } from 'redux'
import {appSetDevice, appSetPushToken, appSetToken, appSetUser, setPopupNotification} from '../../redux/app/action' import { appSetDevice, appSetPushToken, appSetToken, appSetUser, setPopupNotification } from '../../redux/app/action'
import messaging from "@react-native-firebase/messaging"; import messaging from "@react-native-firebase/messaging";
import moment from 'moment' import moment from 'moment'
import { setToken } from '../../api/api' import { setToken } from '../../api/api'
@ -48,6 +48,19 @@ class RegisterProfileScreen extends Component {
initNotification = async () => { initNotification = async () => {
await this.setPermission() 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);
}
const fcmToken = await messaging().getToken() const fcmToken = await messaging().getToken()
console.log('fcmToken', fcmToken) console.log('fcmToken', fcmToken)
if (fcmToken) { if (fcmToken) {
@ -71,83 +84,84 @@ class RegisterProfileScreen extends Component {
async _register() { async _register() {
this.setState({disableButton: true}) this.setState({ disableButton: true })
if (!this.props.device && this.props.push_token) { if (!this.props.device && this.props.push_token) {
const resultSendDevice = await registerDevice(this.props.push_token) const resultSendDevice = await registerDevice(this.props.push_token)
if (resultSendDevice.ok && resultSendDevice.data.success) { if (resultSendDevice.ok && resultSendDevice.data.success) {
this.props.appSetDevice(resultSendDevice.data.device) this.props.appSetDevice(resultSendDevice.data.device)
}
}
let systemName = DeviceInfo.getSystemName();
let deviceId = null
if (systemName == "Android") {
if (!this.props.device) {
Alert.alert(null, 'Cannot get push token or device.', [{ text: 'ok' }])
return;
}
deviceId = this.props.device.id
}
register({
...this.props.user,
device_id: deviceId,
name: this.props.user.name.replace(/\u00a0/g, /\u0020/),
fcm_token: this.props.push_token
}).then(
(res) => {
if (res.ok && res.data.success) {
let token = res.data.token
//this.props.appSetToken(token)
if (res.data.customer) {
this.props.appSetUser(res.data.customer)
this.props.appSetToken(res.data.token)
setToken(token)
Alert.alert(
'',
t('register_success'),
[
{
text: 'OK', onPress: () => {
/*checkPaymentMeter()
.then(result => {
if(result.data){
let data = {
pending_payment: result.data.pending_payment != null ? result.data.pending_payment : 0,
is_notified_electric: result.data.user.is_notified_electric,
is_notified_overdue: result.data.user.is_notified_overdue,
is_notified_meter: result.data.user.is_notified_meter,
payment_id: result.data.payment_id,
notified_meter_at: result.data.notified_meter_at ? result.data.notified_meter_at : moment().format('DD MMM YYYY')
}
this.props.setPopupNotification(data)
}
})*/
this.setState({ isLoading: false }, () => {
this.props.navigation.navigate('HomeScreen', { isLogin: true })
})
}
}
],
{ cancelable: false }
)
//Alert.alert(null, t('register_success'), [{ text: t('ok') }])
//this.props.navigation.navigate('HomeScreen')
}
} else {
this.props.appSetUser(null)
let error_text = res.data.error;
if (res.data.errors && res.data.errors.room[0]) {
error_text = res.data.errors.room[0]
}
Alert.alert(null, error_text, [{ text: t('ok') }])
this.props.navigation.goBack()
} }
} }
let systemName = DeviceInfo.getSystemName();
let deviceId = null
if(systemName == "Android") {
if (!this.props.device) {
Alert.alert(null, 'Cannot get push token or device.', [{ text: 'ok' }])
return;
}
deviceId = this.props.device.id
}
register({
...this.props.user,
device_id: deviceId,
name: this.props.user.name.replace(/\u00a0/g, /\u0020/),
fcm_token: this.props.push_token
}).then(
(res) => {
if (res.ok && res.data.success) {
let token = res.data.token
//this.props.appSetToken(token)
if (res.data.customer) {
this.props.appSetUser(res.data.customer)
this.props.appSetToken(res.data.token)
setToken(token)
Alert.alert(
'',
t('register_success'),
[
{ text: 'OK', onPress: () => {
/*checkPaymentMeter()
.then(result => {
if(result.data){
let data = {
pending_payment: result.data.pending_payment != null ? result.data.pending_payment : 0,
is_notified_electric: result.data.user.is_notified_electric,
is_notified_overdue: result.data.user.is_notified_overdue,
is_notified_meter: result.data.user.is_notified_meter,
payment_id: result.data.payment_id,
notified_meter_at: result.data.notified_meter_at ? result.data.notified_meter_at : moment().format('DD MMM YYYY')
}
this.props.setPopupNotification(data)
}
})*/
this.setState({isLoading:false},() => {
this.props.navigation.navigate('HomeScreen',{isLogin:true})
})
}
}
],
{ cancelable: false }
)
//Alert.alert(null, t('register_success'), [{ text: t('ok') }])
//this.props.navigation.navigate('HomeScreen')
}
} else {
this.props.appSetUser(null)
let error_text = res.data.error;
if(res.data.errors && res.data.errors.room[0]){
error_text = res.data.errors.room[0]
}
Alert.alert(null, error_text, [{ text: t('ok') }])
this.props.navigation.goBack()
}
}
); );
} }
@ -163,11 +177,11 @@ class RegisterProfileScreen extends Component {
<ScrollView showsVerticalScrollIndicator={false} style={{ flex: 1 }}> <ScrollView showsVerticalScrollIndicator={false} style={{ flex: 1 }}>
<View style={styles.container}> <View style={styles.container}>
<View style={styles.step_indicator}> <View style={styles.step_indicator}>
<CustomStepIndicator currentStep={3} totalStep={3} style={{ }} /> <CustomStepIndicator currentStep={3} totalStep={3} style={{}} />
</View> </View>
<View style={styles.logo}> <View style={styles.logo}>
<View style={{ <View style={{
flexGrow: 1,alignItems: 'center', paddingVertical: 20, flexGrow: 1, alignItems: 'center', paddingVertical: 20,
}}> }}>
<Image <Image
style={{ width: 100, height: 100, borderRadius: 50, borderColor: 'white', borderWidth: 2 }} style={{ width: 100, height: 100, borderRadius: 50, borderColor: 'white', borderWidth: 2 }}
@ -206,8 +220,8 @@ class RegisterProfileScreen extends Component {
<View style={[styles.table]}> <View style={[styles.table]}>
<View style={styles.row_title}> <View style={styles.row_title}>
<Text style={styles.title_data}> {t('project')} </Text> <Text style={styles.title_data}> {t('project')} </Text>
<Text style={styles.title_data}> {t('building')} </Text> <Text style={styles.title_data}> {t('building')} </Text>
<Text style={styles.title_data}> {t('room2')} </Text> <Text style={styles.title_data}> {t('room2')} </Text>
</View> </View>
{ {
user !== null && user !== null &&
@ -228,7 +242,7 @@ class RegisterProfileScreen extends Component {
<View style={styles.buttons}> <View style={styles.buttons}>
<View style={styles.row}> <View style={styles.row}>
<CustomButton style={styles.btn_next_register} title={'ยืนยัน'} sizeText={14} <CustomButton style={styles.btn_next_register} title={'ยืนยัน'} sizeText={14}
onPress={this._register} disabled={this.state.disableButton}/> onPress={this._register} disabled={this.state.disableButton} />
</View> </View>
</View> </View>
</LinearGradient> </LinearGradient>