firebase 的 react-native 套件
react-native-firebase-v6
https://invertase.io/blog/react-native-firebase-v6
/* eslint-disable prettier/prettier */
import React from 'react';
import { StyleSheet, Platform, Image, Text, View, ScrollView ,Alert} from 'react-native';
import firebase, { RemoteMessage } from 'react-native-firebase';
import AsyncStorage from '@react-native-community/async-storage';
const iosConfig = {
//////你的設定
};
const itHelpApp = firebase.initializeApp(iosConfig);
export default class App extends React.Component {
constructor() {
super();
this.state = {
isSigninInProgress: "",
};
}
componentDidMount() {
// console.log('User APNS Token:', firebase.messaging().getAPNSToken());
const fcmToken = firebase.messaging().getToken();
console.log('User fcm Token:', fcmToken);
this.updata();
this.checkPermission();
this.createNotificationListeners(); //add this line
this.messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
// Process your message as required
});
}
componentWillUnmount() {
this.notificationListener();
this.notificationOpenedListener();
this.messageListener();
}
//1
async checkPermission() {
const enabled = await firebase.messaging().hasPermission();
if (enabled) {
this.getToken();
} else {
this.requestPermission();
}
}
//2
async requestPermission() {
try {
await firebase.messaging().requestPermission();
// User has authorised
this.getToken();
} catch (error) {
// User has rejected permissions
console.log('permission rejected');
}
}
//3
async getToken() {
let fcmToken = await AsyncStorage.getItem('fcmToken');
if (!fcmToken) {
fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
// user has a device token
await AsyncStorage.setItem('fcmToken', fcmToken);
}
}
}
async createNotificationListeners() {
/*
* Triggered when a particular notification has been received in foreground
* */
this.notificationListener = firebase.notifications().onNotification((notification) => {
const { title, body } = notification;
this.showAlert(title, body);
});
/*
* If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
* */
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
const { title, body } = notificationOpen.notification;
this.showAlert(title, body);
});
/*
* If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
* */
const notificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
const { title, body } = notificationOpen.notification;
this.showAlert(title, body);
}
/*
* Triggered for data only payload in foreground
* */
this.messageListener = firebase.messaging().onMessage((message) => {
//process data message
console.log(JSON.stringify(message));
});
}
showAlert(title, body) {
Alert.alert(
title, body,
[
{ text: 'OK', onPress: () => console.log('OK Pressed') },
],
{ cancelable: false },
);
}
// async googleLogin() {
// try {
// // add any configuration settings here:
// await GoogleSignin.configure();
// const data = await GoogleSignin.signIn();
// // create a new firebase credential with the token
// const credential = firebase.auth.GoogleAuthProvider.credential(data.idToken, data.accessToken)
// // login with credential
// const firebaseUserCredential = await firebase.auth().signInWithCredential(credential);
// console.warn(JSON.stringify(firebaseUserCredential.user.toJSON()));
// } catch (e) {
// console.error(e);
// }
// }
render() {
return (
<ScrollView>
<View style={styles.container}>
{/* <Image source={require('./assets/ReactNativeFirebase.png')} style={[styles.logo]} /> */}
<Text style={styles.welcome}>
Welcome to {'\n'} React Native Firebase
</Text>
<Text style={styles.instructions}>
To get started, edit App.js
</Text>
{Platform.OS === 'ios' ? (
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
) : (
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Cmd+M or shake for dev menu
</Text>
)}
<View style={styles.modules}>
<Text style={styles.modulesHeader}>The following Firebase modules are pre-installed:</Text>
{firebase.admob.nativeModuleExists && <Text style={styles.module}>admob()</Text>}
{firebase.analytics.nativeModuleExists && <Text style={styles.module}>analytics()</Text>}
{firebase.auth.nativeModuleExists && <Text style={styles.module}>auth()</Text>}
{/* https://rnfirebase.io/docs/v5.x.x/auth/social-auth */}
{firebase.config.nativeModuleExists && <Text style={styles.module}>config()</Text>}
{firebase.crashlytics.nativeModuleExists && <Text style={styles.module}>crashlytics()</Text>}
{firebase.database.nativeModuleExists && <Text style={styles.module}>database()</Text>}
{firebase.firestore.nativeModuleExists && <Text style={styles.module}>firestore()</Text>}
{firebase.functions.nativeModuleExists && <Text style={styles.module}>functions()</Text>}
{firebase.iid.nativeModuleExists && <Text style={styles.module}>iid()</Text>}
{firebase.links.nativeModuleExists && <Text style={styles.module}>links()</Text>}
{firebase.messaging.nativeModuleExists && <Text style={styles.module}>messaging()</Text>}
{firebase.notifications.nativeModuleExists && <Text style={styles.module}>notifications()</Text>}
{firebase.perf.nativeModuleExists && <Text style={styles.module}>perf()</Text>}
{firebase.storage.nativeModuleExists && <Text style={styles.module}>storage()</Text>}
</View>
{/* <GoogleSigninButton
style={{ width: 192, height: 48 }}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
onPress={this.googleLogin}
disabled={this.state.isSigninInProgress} /> */}
{/* {this.Todos()} */}
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
// justifyContent: 'center',
// alignItems: 'center',
backgroundColor: '#F5FCFF',
},
logo: {
height: 120,
marginBottom: 16,
marginTop: 64,
padding: 10,
width: 135,
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
modules: {
margin: 20,
},
modulesHeader: {
fontSize: 16,
marginBottom: 8,
},
module: {
fontSize: 14,
marginTop: 4,
textAlign: 'center',
}
});