Last active
September 6, 2019 13:32
-
-
Save blueberry404/e20d25ee035b2d98aef17c565df44e5e to your computer and use it in GitHub Desktop.
Handling permissions for Push notifications using Firebase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {Component} from 'react'; | |
import { AsyncStorage } from 'react-native'; | |
import firebase from 'react-native-firebase'; | |
export default class App extends Component { | |
async componentDidMount() { | |
this.checkPermission(); | |
} | |
//1 | |
async checkPermission() { | |
const enabled = await firebase.messaging().hasPermission(); | |
if (enabled) { | |
this.getToken(); | |
} else { | |
this.requestPermission(); | |
} | |
} | |
//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); | |
} | |
} | |
} | |
//2 | |
async requestPermission() { | |
try { | |
await firebase.messaging().requestPermission(); | |
// User has authorised | |
this.getToken(); | |
} catch (error) { | |
// User has rejected permissions | |
console.log('permission rejected'); | |
} | |
} | |
render() { | |
return ( | |
<View style={{flex: 1}}> | |
<Text>Welcome to React Native!</Text> | |
</View> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment