Skip to content

Instantly share code, notes, and snippets.

@juanchoperezj
Created October 3, 2018 12:45
Show Gist options
  • Save juanchoperezj/93cbd1f9781a52340387f05501fc5644 to your computer and use it in GitHub Desktop.
Save juanchoperezj/93cbd1f9781a52340387f05501fc5644 to your computer and use it in GitHub Desktop.
import { AsyncStorage, Alert, Platform } from 'react-native';
import firebase from 'react-native-firebase';
const displayNotificationFromCustomData = message => {
if (message.data && message.data.title) {
let notification = new firebase.notifications.Notification();
notification = notification
.setTitle(message.data.title)
.setBody(message.data.body)
.setData(message.data);
if (Platform.OS === 'android') {
notification.android.setPriority(firebase.notifications.Android.Priority.High);
notification.android.setChannelId(notification.data.channelId);
}
firebase.notifications().displayNotification(notification);
}
};
export const registerHeadlessListener = async message => {
await AsyncStorage.setItem('headless', new Date().toISOString());
displayNotificationFromCustomData(message);
};
// these callback will be triggered only when app is foreground or background
export const registerAppListener = navigator => {
this.notificationListener = firebase.notifications().onNotification(notification => {
// Build a channel
const channel = new firebase.notifications.Android.Channel(
'reply_secrets',
'Replies for secrets',
firebase.notifications.Android.Importance.Max
).setDescription('Channel description');
if (Platform.OS === 'android') {
firebase.notifications().android.createChannel(channel);
notification.android.setChannelId(notification.data.channelId).android.setSmallIcon('ic_notification');
}
firebase.notifications().displayNotification(notification);
});
this.notificationOpenedListener = firebase.notifications().onNotificationOpened(notificationOpen => {
const notif = notificationOpen.notification;
const notification = new firebase.notifications.Notification();
if (Platform.OS === 'android') notification.android.setChannelId(notification.data.channelId);
const { data } = notif;
if (data.secretId) {
Alert.alert('Title', 'Body', [
{
text: 'Ver',
onPress: () => action(),
},
{
text: 'Cerrar',
},
]);
}
});
this.onTokenRefreshListener = firebase.messaging().onTokenRefresh(token => {
console.log(`TOKEN (refreshUnsubscribe), ${token}`);
});
this.messageListener = firebase.messaging().onMessage(message => displayNotificationFromCustomData(message));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment