Reputation: 827
I'm using Firebase cloud functions to send a remote notification to a specific device I got his FCM Token, and I receive it and works very well,
Here is my code to send a notification by Cloud functions
const functions = require("firebase-functions");
const admin = require("firebase-admin");
var serviceAccount = require("./serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://-----.firebaseio.com"
});
exports.sendPushR = functions.database
.ref("/request/{pid}/orders/{orderid}")
.onCreate(async (snapshot, context) => {
const registrationTokens = snapshot.val().token;
const event = context.params;
const afterData = snapshot.val();
const username = snapshot.val().username;
const payload = {
notification: {
title: "New Order",
body: `You received a new order from ${username} check it now! `,
sound: "default",
icon: "default"
}
};
try {
const response = await admin
.messaging()
.sendToDevice(registrationTokens, payload);
console.log("Successfully sent message:", response);
} catch (error) {
console.log("Error sending message:", error);
}
return null;
});
And in the Home screen App
async componentDidMount() {
//BackHandler.addEventListener("hardwareBackPress", this.backPressed);
this.notificationInitListener = await firebase
.notifications()
.getInitialNotification()
.then(notificationOpen => {
if (notificationOpen) {
console.log(notificationOpen);
setTimeout(() => {
this.props.navigation.navigate("Notifications");
}, 5000);
console.log("1---OPEND");
firebase.notifications().removeAllDeliveredNotifications();
console.log("1---OPEND-After");
}
});
this.removeNotificationOpenedListener = firebase
.notifications()
.onNotificationOpened(notificationOpen => {
// Get the action triggered by the notification being opened
// const action = notificationOpen.action;
// Get information about the notification that was opened
// const notification = notificationOpen.notification;
if (notificationOpen) {
this.props.navigation.navigate("Notifications");
console.log("OPEND");
firebase.notifications().removeAllDeliveredNotifications();
console.log("OPEND-After");
}
});
}
Route
const HomeStack = createStackNavigator(
{
Home: {
screen: Home,
navigationOptions: ({ navigation }) => ({
title: "Home",
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerRight: (
<TouchableOpacity
onPress={() => navigation.navigate("Notifications")}
style={{ margin: 10 }}
>
<Icon name="ios-notifications" size={28} color="#1DA1F2" />
</TouchableOpacity>
)
})
},
MapScreen: {
screen: MapScreen,
navigationOptions: {
title: "Map"
}
},
ProviderProfile: {
screen: ProviderProfile
},
GalleryDetails: {
screen: GalleryDetails,
navigationOptions: {
title: "Gallery Details"
}
},
Order: {
screen: Order,
navigationOptions: {
title: "Order"
}
},
Favorites: {
screen: UserFavorites,
navigationOptions: ({ navigation }) => ({
title: "My Favorites!",
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />
})
},
Notifications: {
screen: Notifications,
navigationOptions: {
title: "Notifications"
}
}
},
{
defaultNavigationOptions
}
);
Now I have two issues:
But the under function "onNotificationOpened" works very well when the app is still in the background
Demo https://vimeo.com/350006721
Upvotes: 3
Views: 9032
Reputation: 1159
Best way to handle navigation on notification opening is to handle them in a splash screen. this will give you more flexibility. just check if the app is opened by notification, in componentDidMount
, And navigate to the desired screen. you can use createSwitchNavigator
to prevent android back button and ios gesture, from going back to the splash screen.
I think the second issue when I receive a notification "when app killed" and click to open it, it's opened very well and navigate me to "Notifications Screen" But in every time after I open the app without click to any notification it navigates me to "Notifications Screen", SO How can I remove the previous notification "remove the listener in getInitialNotification "
To solve this issue you have to save the messageId
/notificationId
in AsyncStorage
after processing the notification and before navigating to the new screen. And just before processing the notification you can check if that notification is already processed.
the steps you have to take:
1- check if the notificationId
is processed before ( this can be an AsyncStorage
call).
2- if processed: clear AsyncStorage
, 'cause we don't need it anymore
3- if not: add the notificationId
to AsyncStorage and navigate to the new screen
Upvotes: 1
Reputation: 13578
You don't have explained what you expected.. but I think you don't want to start with that notification-screen, but with the Home-Screen.
For this, you can use the initialRouteName
as second parameter for your createStackNavigator
method (see example at the very bottom of this Page: https://reactnavigation.org/docs/en/stack-navigator.html)
Give it a try, and if solved, go hunt for the second issue (I prefer to solve issues Step by Step)
Upvotes: 1