Redirect to a specific screen from React Native Firebase Push Notifications based on a Deeplink - firebase

I got a problem,
1 ) I'm using Firebase to send remote Push Notifications, i test by sending from FCM tester.
2 ) I've activated Deep-Linking in my project and started to use it.
3 ) In FCM tester i pass this key value into "notifications.data" :
{ "link" : "MY_LINK" }
Now i want my app to be able to recognize there is a deepLink in it & read it.
Which i achieved to do somehow but not the way i was looking for.
What i did :
NotificationContextProvider.ts
useEffect(() => {
const unsubscribeClosedApp = messaging().onNotificationOpenedApp(
remoteMessage => {
addNotification(remoteMessage);
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
redirectFromKey(remoteMessage.data?.redirection);
console.log(remoteMessage.data, 'remote message data');
console.log(remoteMessage, 'remote message full');
console.log(remoteMessage.notification?.body, 'remote message body');
console.log(remoteMessage.notification?.title, 'remote message title');
if (remoteMessage.data?.link === 'https://[MY-LINK]/TnRV') {
console.log(remoteMessage.data?.link, 'Deeplink detected & opened');
navigation.navigate({
name: 'Logged',
params: {
screen: 'Onboarded',
params: {
screen: 'LastAnalyse',
},
},
});
}
},
);
And it's working fine but it's not based on reading a link, but by comparing a value and it's not what i'm trying to achieve.
Firebase Doc' give us a way to do this : https://rnfirebase.io/dynamic-links/usage#listening-for-dynamic-links
This is what Firebase suggests :
import dynamicLinks from '#react-native-firebase/dynamic-links';
function App() {
const handleDynamicLink = link => {
// Handle dynamic link inside your own application
if (link.url === 'https://invertase.io/offer') {
// ...navigate to your offers screen
}
};
useEffect(() => {
const unsubscribe = dynamicLinks().onLink(handleDynamicLink);
// When the component is unmounted, remove the listener
return () => unsubscribe();
}, []);
return null;
}
And i have no clue how to make it works.
I got to mention that deep-links are correctly setup in my project and working fine, my code is in Typescript.
Basicaly you can find on this web page what i'm trying to achieve but i want to use Firebase/messaging + Dynamic links. My project don't use local notifications and will never do : https://medium.com/tribalscale/working-with-react-navigation-v5-firebase-cloud-messaging-and-firebase-dynamic-links-7d5c817d50aa
Any idea ?

I looked into this earlier, it seems that...
You can't send a deep link in an FCM message using the firebase Compose Notification UI.
You probably can send a deep link in an FCM message using the FCM REST API. More in this stackoverflow post.
The REST API looks so cumbersome to implement you're probably better off the way you're doing it: Using the firebase message composer with a little data payload, and your app parses the message data with Invertase messaging methods firebase.messaging().getInitialNotification() and firebase.messaging().onNotificationOpenedApp().
As for deep linking, which your users might create in-app when trying to share something, or you might create in the firebase Dynamic Links UI: For your app to notice actual deep links being tapped on the device, you can use Invertase dynamic links methods firebase.dynamicLinks().getInitialLink() and firebase.dynamicLinks().onLink().

Related

Remove notification after a certain time in React Native (#react-native-firebase/messaging)

I have push notifications working in React Native using #react-native-firebase/messaging. I am using FCM on the backend, and it is currently showing the OS lock screen notifications on iOS and Android.
I want to clear a given notification after a certain time, or after an amount of time has passed. Is there a way to do this? Right now when I send a notification it will stick around for days if I don't click on it. I would like to take a notification down after say an hour, or at 4pm, or whatever. Front-end and/or back-end solutions welcome.
I had assumed that the "ttl" (time to live) parameter did this, but this is not the case.
you could use a background handler like react-native-background-fetch
In your onMessage or backgroundMessage schedule a backgroundTask for your desired time with scheduleTask().
You could use react-native-push-notification to display the notification, which has an method cancelLocalNotifications() to cancel notifications
In the task you could clear the notification depending on the id
PushNotification.configure({
onNotification: (notification) => {
var {id} = remoteMessage.data
BackgroundFetch.configure({
minimumFetchInterval: 15
}, async (taskId) => {
PushNotification().cancelLocalNotifications(id)
BackgroundFetch.finish(taskId);
})
BackgroundFetch.scheduleTask({
taskId: id,
forceAlarmManager: true,
delay: 5000
});
}
})
TTL parameter only specifies the delivery of the notification to the user device. E.g. Still deliver the message after the phone was offline for 2 hours or not.
I'm not sure if there is a way with the default firebase package, but the more advanced version of it seems to be able to handle that use case:
https://notifee.app/react-native/reference/canceldisplayednotification
I think you should be able to call that method in a background task (e.g. after receiving another (silent) notification).
Unfortunately I couldn’t test it myself yet.
On iOS you you can use the badge setting. If you set it to 0, it will remove all notifications. For your case you could schedule a "cleanup" task that triggers the below request after a certain amount of time.
{
message: {
notification: {
body: "" // has to be empty
},
android: {
notification: {
channel_id: 'some_channel'
}
},
apns: {
payload: {
aps: {
category: 'some_category',
badge: 0
}
}
},
token: device_token
}
}
Unfortunately, I have not found a similar solution for android yet.

Permissions in Firebase notifications

I have created this function in Google Cloud Platform associated with Firebase Realtime Database. The function sends a notification to mobile applications when something appears in the database.
As you can see below I set the priorities so that the notification will be noticed by the user
var message = {
token: tokenSnapshot,
notification: {
title: "Title",
body: "Body",
},
android: {
priority: 'high',
notification: {
sound: 'default',
priority: 'high',
visibility: 'public'
}
},
};
Unfortunately, it doesn't do anything. The notification comes but the user sees when he checks manually if something has come
I use a standard approach in the application
messaging().enable.setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', JSON.stringify(remoteMessage));
})
Is there any way for notifications to be with sound, vibration and to appear on the lock screen?
I haven't used the react-native-push-notification library yet. Can this library help in this?
If you are using firebase-cloud messaging i suggest using firebase in your app.
https://rnfirebase.io/messaging/usage
Make sure you follow the initial set up first.
Please read more about this here. https://rnfirebase.io/

How do I use cordova firebase.dynamiclinks plugin in Ionic 4?

I want to use Cordova Firebase Dynamiclinks plugin : https://github.com/chemerisuk/cordova-plugin-firebase-dynamiclinks#installation in my Ionic 4 App.
There is an Ionic-native-plugin usage for this too : npm install #ionic-native/firebase-dynamic-links and usage :
import { FirebaseDynamicLinks } from '#ionic-native/firebase-dynamic-links/ngx';
constructor(private firebaseDynamicLinks: FirebaseDynamicLinks) { }
...
this.firebaseDynamicLinks.onDynamicLink()
.subscribe((res: any) => console.log(res), (error:any) => console.log(error));
Issue is : I want to use createDynamicLink(parameters) method available in Cordova Firebase Dynamiclinks plugin but Ionic-native-plugin says
Property 'createDynamicLink' does not exist on type 'FirebaseDynamicLinks'.
Therefore, I need to use Cordova Firebase Dynamiclinks directly and I tried doing using it like
import { cordova } from '#ionic-native/core';
...
cordova.plugins.firebase.dynamiclinks.createDynamicLink({
link: "https://google.com"
}).then(function(url) {
console.log("Dynamic link was created:", url);
});
But got error
Property 'plugins' does not exist on type '(pluginObj: any, methodName: string, config: CordovaOptions, args: IArguments | any[]) => any'.
Also tried removing import
cordova.plugins.firebase.dynamiclinks.createDynamicLink({
link: "https://google.com"
}).then(function(url) {
console.log("Dynamic link was created:", url);
});
And got this
Property 'firebase' does not exist on type 'CordovaPlugins'.
What is the correct usage of cordova plugins?
Update
Ionic-native-plugin now contains all the methods available in Cordova Firebase Dynamiclinks plugin.
I believe this is more fitting of a comment, but I don't quite have the reputation for it yet.
Currently, there is a PR open in the #ionic-team/ionic-native repo (here). This exposes the extra methods, but until then you can use the original repo here to get your desired effect. In order to install the repo you will have to follow the directions in the Developer guide here. Cheers!
I have developed an ionic 5 app that uses Firebase Dynamic Links and it works great but it took some effort. I watched videos to understand how Firebase Dynamic Links work but there is certainly much that is not shown.
To answer the original question you can always manually create a dynamic link which is what I do in our solution. We created a dynamic link that would help users onboard (register an account). Our dynamic link has custom onboardingId which originates from the backend process and the link is presented to the user via SMS text message.
This is in app.component.ts constructor
Here is some code that happens when the user clicks the dynamic link:
// Handle the logic here after opening the app (app is already installed) with the Dynamic link
this.firebaseDynamicLinks.onDynamicLink().subscribe((res: any) => {
console.log('app was opened with dynamic link');
console.log(res);
/* This only fires on subsequent calls and not on app start 20220208 STR
console.log(JSON.stringify(res)); //"{"deepLink":"https://localhost/onboard?onboardingId=8ed634b0-53b7-4a0f-b67e-12c06019982a","clickTimestamp":1643908387670,"minimumAppVersion":0}"
var dynamicLink = JSON.parse(JSON.stringify(res));
var deepLink = dynamicLink.deepLink;
console.log(deepLink);
if (deepLink.indexOf("onboard")>=0){
this.isOnboarding = true;
}
alert("deepLink ="+ deepLink);
*/
}, (error:any) => {
console.log(error)
});
I originally thought that Firebase handles all of the magic if the user doesn't have the app installed. I was wrong! You MUST also handle the code to pickup the dynamic link after the app is installed.
The code below will read the dynamic link from the clipboard and survives the app install process. Placed in app.component.ts ngOnInit().
this.platform.ready().then(() => {
this.firebaseDynamicLinks.getDynamicLink().then((data) => {
//added 20220208 STR try to help open the deep link if app is just installed
if (data != null) {
console.log(JSON.stringify(data));
//alert("initializeApp():"+JSON.stringify(data));
var dynamicLink = JSON.parse(JSON.stringify(data));
var deepLink = dynamicLink.deepLink;
console.log("initializeApp():"+deepLink);
if (deepLink != "") {
if (deepLink.indexOf("onboard")>=0){
this.isOnboarding = true;
this.deepLinkToOnboard(deepLink);
}
}
}
});}
So to handle dynamic links after you have the Firebase plugin installed, you must have two sections of code; one for handling if the app is already installed and another for handling the dynamic link if the app is not installed.

How to use Sign-In User ID to send push notifications

I have some users signed into my actions-on-google app via Google Sign-In ( https://developers.google.com/actions/identity/google-sign-in )
I want to sent push notifications to one of those users.
For getting push notifications work with actions in the first place, I tried this sample: https://github.com/actions-on-google/dialogflow-updates-nodejs/blob/master/functions/index.js but I only can get this to work without this commit: https://github.com/actions-on-google/dialogflow-updates-nodejs/commit/c655062047b49e372da37af32376bd06d837fc7f#diff-1e53ef2f51bd446c876676ba83d7c888
It works fine, but I think const userID = conv.user.id; returns the deprecated Anonymous User ID. The commit suggests to use const userID = conv.arguments.get('UPDATES_USER_ID'); which returns undefined.
I use this nodejs code to send the push notifications.
const request = require('request');
const {JWT} = require('google-auth-library');
const serviceAccount = require('./service-account.json');
let jwtClient = new JWT(
serviceAccount.client_email, null, serviceAccount.private_key,
['https://www.googleapis.com/auth/actions.fulfillment.conversation'],
null
);
jwtClient.authorize((authErr, tokens) => {
let notification = {
userNotification: {
title: process.argv[2],
},
target: {
userId: USERID,
intent: 'tell_latest_status',
// Expects a IETF BCP-47 language code (i.e. en-US)
locale: 'en-US'
},
};
request.post('https://actions.googleapis.com/v2/conversations:send', {
'auth': {
'bearer': tokens.access_token,
},
'json': true,
'body': {
'customPushMessage': notification, 'isInSandbox': true
},
}, (reqErr, httpResponse, body) => {
console.log(httpResponse.statusCode + ': ' + httpResponse.statusMessage);
});
});
I simply can't get this to work with the const userID = conv.arguments.get('UPDATES_USER_ID'); version, because as I said
When I use conv.user.profile.payload.sub as suggested here: https://developers.google.com/actions/identity/user-info the AoG API returns "SendToConversation response: Invalid user id for target."
Is there any way to make this work with Google Sign-In?
Has anyone made this work? I mean with the UPDATES_USER_ID field?
I already created an issue on the samples repo: https://github.com/actions-on-google/dialogflow-updates-nodejs/issues/15 but I was sent here.
Thanks!
While researching why I sometimes got undefined I found an answer on this question that solved my issue.
I've found solution for this problem. While getting UPDATES_USER_ID
conv.arguments.get() only works for first attempt. So, while building
your action you must save it. If you didn't store or save, you can
reset your profile and try again, you will be able to get.
You can reset your user profile for the action here.

how to enable firebase notifications in ionic android application

i want to build an application and use firebase for notification done a lot of search over google but did not find any good guide and solution , everything i tried ended into some errors . i tried ionic docs but they are all messy after the ionic v4 they shows everything about v4 i have my app almost finished up just this thing remains .
i will appreciate any help .
Any idea how to proceed? I'm most probably not configuring Firebase properly. I have placed google-services.json in the root directory, no problems there. but after that its all out of my understanding
AN ERROR OCCURRED WHILE RUNNING ionic cordova plugin add phonegap-plugin-push --variable SENDER_ID-150482406038 --SAVE EXIT CODE 1
Got this Working . Thanks everyone for help!
refrences used-
https://ionicframework.com/docs/v3/native/push/
https://github.com/phonegap/phonegap-plugin-push
works for
ionic 3.20.1
cordova 8.1.2
steps i followed
Removed my android platform using ionic cordova platform
removeandroid then i created it agin ionic cordova platform add
android. just to avoid any errors which my be there with my old
android version.
Got the google-services.json and placed it in the
rootDirectoryOfApp\platforms\android\app
then i run $ ionic cordova plugin add phonegap-plugin-push $ npm
install --save #ionic-native/push#4
Edit config.xml look for <platform name="android"> under that i
wrote <resource-file src="google-services.json"
target="app/google-services.json" />
Edit package.json look for "phonegap-plugin-push" and edit it
something like this
"phonegap-plugin-push": {
"ANDROID_SUPPORT_V13_VERSION": "27.+", // already there
"FCM_VERSION": "11.6.2", // already there
"SENDER_ID": "numeric key obtain from firebase console" // added
},
Open app.module.ts and import import { Push } from
'#ionic-native/push'; add Push under providers there ...
providers: [
StatusBar,
SplashScreen,
Push, ....
Then in a provider
i imported import { Push, PushObject, PushOptions } from '#ionic-native/push';
then in costructor i added private push: Push,
and in the class of that provider i wrote a function like below
pushSetup(){
// to check if we have permission
this.push.hasPermission()
.then((res: any) => {
if (res.isEnabled) {
console.log('We have permission to send push notifications');
} else {
console.log('We do not have permission to send push notifications');
}
});
// Create a channel (Android O and above). You'll need to provide the id, description and importance properties.
this.push.createChannel({
id: "testchannel1",
description: "My first test channel",
// The importance property goes from 1 = Lowest, 2 = Low, 3 = Normal, 4 = High and 5 = Highest.
importance: 3
}).then(() => console.log('Channel created'));
// Delete a channel (Android O and above)
this.push.deleteChannel('testchannel1').then(() => console.log('Channel deleted'));
// Return a list of currently configured channels
this.push.listChannels().then((channels) => console.log('List of channels', channels))
// to initialize push notifications
const options: PushOptions = {
android: {
senderID:"150482406038",
},
ios: {
alert: 'true',
badge: true,
sound: 'false'
},
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => console.log('Received a notification', notification));
pushObject.on('registration').subscribe((registration: any) => console.log('Device registered', registration));
pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
}
Now imported that provider where I want to use that , and called
that function from there . but call it only after
this.platform.ready().then(() => { or when a successful login.
I have shared this because i found it little difficult and got confusing guides over web
Please comment if you found it wrong or not working in your case.
I have been using this tutorial: https://medium.com/#felipepucinelli/how-to-add-push-notifications-in-your-cordova-application-using-firebase-69fac067e821 and Android push notifications worked out of the box. Good luck!
^ you might wanna try the cordova-plugin-firebase plugin as Chrillewoodz has mentioned

Resources