Not receiving fcm message when app is close in Android with react-native-firebase - react-native

I followed the steps mentioned here.
Now, I'm receiving messages when the app is in foreground via firebase.messaging().onMessage and in the background, via a headless task I defined according to the same guide, but I don't receive messages when the app is closed
I am using one plus 6, where I even disabled the Battery optimize option for my phone, tried installing a signing build but none of it is working.
This is my bgMessaging.js
import firebase from 'react-native-firebase';
// Optional flow type
import type { RemoteMessage } from 'react-native-firebase';
export default async (message: RemoteMessage) => {
const channel = new firebase.notifications.Android.Channel('channel-id', 'channel-Name', firebase.notifications.Android.Importance.Max)
.setDescription('Description');
firebase.notifications().android.createChannel(channel);
const localNotification = new firebase.notifications.Notification()
.setNotificationId(message.messageId)
.setTitle("Title")
.setSubtitle('Test')
.setBody("Body")
.setData(message.data)
.android.setChannelId('channel-id')
.android.setAutoCancel(false)
.android.setPriority(firebase.notifications.Android.Priority.High);
firebase.notifications().displayNotification(localNotification);
return Promise.resolve();
}
Even added this on AndroidManifest.xml
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
Am I missing anything on native side?

You can go to http://pushtry.com/ and set the jSON as :
{
"to":FCM_TOKEN
"notification": {
"body": "body",
"title": "title"
},
"priority":'high'
}

Related

Implementing app tracking transparency permission request on Expo 45

I have a managed-expo (sdk 45) application and for some reason apple rejects my application because they are unable to locate the App Tracking Transparency permission request. I know it has something to do with expo-ads-admob. I am getting this message:
Please explain where we can find the App Tracking Transparency permission request in your app. The request should appear before any data is collected that could be used to track the user.
If you've implemented App Tracking Transparency but the permission request is not appearing on devices running the latest OS, please review the available documentation and confirm App Tracking Transparency has been correctly implemented.If your app does not track users, update your app privacy information in App Store Connect to undeclare tracking. You must have the Account Holder or Admin role to update app privacy information.
I'm using expo-ads-admob and this is how I did it (docs):
I installed expo-tracking-transparency
and added the function on the first part of the application (App.tsx)
import * as React from "react";
import { requestTrackingPermissionsAsync } from "expo-tracking-transparency";
export default function App() {
React.useEffect(() => {
(async () => {
const { status } = await requestTrackingPermissionsAsync();
if (status === "granted") {
console.log("Yay! I have user permission to track data");
}
})();
}, []);
return (
<MainApplication />
);
}
I also added
"plugins": [
[
"expo-tracking-transparency",
{
"userTrackingPermission": "This identifier will be used to deliver personalized ads to you."
}
]
]
To app.json
Then I use the component (everywhere in the app) like this:
<AdMobBanner
bannerSize={
Platform.OS === "ios" ? "fullBanner" : "smartBannerLandscape"
}
adUnitID={
Platform.OS == "ios"
? "IOS_ADMOB_CODE"
: "ANDROID_ADMOB_CODE"
}
servePersonalizedAds={false}
onDidFailToReceiveAdWithError={() => {}}
onAdViewDidReceiveAd={() => {}}
/>
It works, but iOS keep rejecting my application claiming they can't find the permission. I looked everywhere and saw this is the right way to implement this but unfortunately it didn't work.
Thanks in advance!
if you dont have infoplist go to and add the Description here.
enter image description here

How to setup sendSignInLinkToEmail() from Firebase in react-native?

Working on a react-native project using #react-native-firebase/app v6 we recently integrated signing in with a "magic link" using auth.sendSignInLinkToEmail
We couldn't find a good example on how to setup everything in react-native and had different problems like
- auth/invalid-dynamic-link-domain - The provided dynamic link domain is not configured or authorized for the current project.
- auth/unauthorized-continue-uri - Domain not whitelisted by project
Searching for information and implementing the "magic link login" I've prepared a guide on how to have this setup in react-native
Firebase project configuration
Open the Firebase console
Prepare firebase instance (Email Link sign-in)
open the Auth section.
On the Sign in method tab, enable the Email/Password provider. Note that email/password sign-in must be enabled to use email link sign-in.
In the same section, enable Email link (passwordless sign-in) sign-in method.
On the Authorized domains tab (just bellow)
Add any domains that will be used
For example the domain for the url from ActionCodeSettings needs to be included here
Configuring Firebase Dynamic Links
For IOS - you need to have an ios app configured - Add an app or specify the following throughout the firebase console
Bundle ID
App Store ID
Apple Developer Team ID
For Android - you just need to have an Android app configured with a package name
Enable Firebase Dynamic Links - open the Dynamic Links section
“Firebase Auth uses Firebase Dynamic Links when sending a link that is meant to be opened in a mobile application.
In order to use this feature, Dynamic Links need to be configured in the Firebase Console.”
(ios only) You can verify that your Firebase project is properly configured to use Dynamic Links in your iOS app by opening
the following URL: https://your_dynamic_links_domain/apple-app-site-association
It should show something like:
{
"applinks": {
"apps": [],
"details": [
{
"appID": "AP_ID123.com.example.app",
"paths": [
"NOT /_/", "/"
]
}
]
}
}
IOS Xcode project configuration for universal links
Open the Xcode project and go to the Info tab create a new URL type to be used for Dynamic Links.
Enter a unique value in Identifier field and set the URL scheme field to be your bundle identifier, which is the default URL scheme used by Dynamic Links.
In the Capabilities tab, enable Associated Domains and add the following to the Associated Domains list: applinks:your_dynamic_links_domain
(!) This should be only the domain - no https:// prefix
Android
Android doesn’t need additional configuration for default or custom domains.
Packages
A working react-native project setup with react-native-firebase is required, this is thoroughly covered in the library own documentation, here are the specific packages we used
Note: using the dynamicLinks package can be replaced with react-native's own Linking module and the code would be almost identical
Exact packages used:
"#react-native-firebase/app": "^6.7.1",
"#react-native-firebase/auth": "^6.7.1",
"#react-native-firebase/dynamic-links": "^6.7.1",
Sending the link to the user email
The module provides a sendSignInLinkToEmail method which accepts an email and action code configuration.
Firebase sends an email with a magic link to the provided email. Following the link has different behavior depending on the action code configuration.
The example below demonstrates how you could setup such a flow within your own application:
EmailLinkSignIn.jsx
import React, { useState } from 'react';
import { Alert, AsyncStorage, Button, TextInput, View } from 'react-native';
import auth from '#react-native-firebase/auth';
const EmailLinkSignIn = () => {
const [email, setEmail] = useState('');
return (
<View>
<TextInput value={email} onChangeText={text => setEmail(text)} />
<Button title="Send login link" onPress={() => sendSignInLink(email)} />
</View>
);
};
const BUNDLE_ID = 'com.example.ios';
const sendSignInLink = async (email) => {
const actionCodeSettings = {
handleCodeInApp: true,
// URL must be whitelisted in the Firebase Console.
url: 'https://www.example.com/magic-link',
iOS: {
bundleId: BUNDLE_ID,
},
android: {
packageName: BUNDLE_ID,
installApp: true,
minimumVersion: '12',
},
};
// Save the email for latter usage
await AsyncStorage.setItem('emailForSignIn', email);
await auth().sendSignInLinkToEmail(email, actionCodeSettings);
Alert.alert(`Login link sent to ${email}`);
/* You can also show a prompt to open the user's mailbox using 'react-native-email-link'
* await openInbox({ title: `Login link sent to ${email}`, message: 'Open my mailbox' }); */
};
export default EmailLinkSignIn;
We're setting handleCodeInApp to true since we want the link from the email to open our app and be handled there. How to configure and handle this is described in the next section.
The url parameter in this case is a fallback in case the link is opened from a desktop or another device that does not
have the app installed - they will be redirected to the provided url and it is a required parameter. It's also required to
have that url's domain whitelisted from Firebase console - Authentication -> Sign in method
You can find more details on the supported options here: ActionCodeSettings
Handling the link inside the app
Native projects needs to be configured so that the app can be launched by an universal link as described
above
You can use the built in Linking API from react-native or the dynamicLinks #react-native-firebase/dynamic-links to intercept and handle the link inside your app
EmailLinkHandler.jsx
import React, { useState, useEffect } from 'react';
import { ActivityIndicator, AsyncStorage, StyleSheet, Text, View } from 'react-native';
import auth from '#react-native-firebase/auth';
import dynamicLinks from '#react-native-firebase/dynamic-links';
const EmailLinkHandler = () => {
const { loading, error } = useEmailLinkEffect();
// Show an overlay with a loading indicator while the email link is processed
if (loading || error) {
return (
<View style={styles.container}>
{Boolean(error) && <Text>{error.message}</Text>}
{loading && <ActivityIndicator />}
</View>
);
}
// Hide otherwise. Or show some content if you are using this as a separate screen
return null;
};
const useEmailLinkEffect = () => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const handleDynamicLink = async (link) => {
// Check and handle if the link is a email login link
if (auth().isSignInWithEmailLink(link.url)) {
setLoading(true);
try {
// use the email we saved earlier
const email = await AsyncStorage.getItem('emailForSignIn');
await auth().signInWithEmailLink(email, link.url);
/* You can now navigate to your initial authenticated screen
You can also parse the `link.url` and use the `continueurl` param to go to another screen
The `continueurl` would be the `url` passed to the action code settings */
}
catch (e) {
setError(e);
}
finally {
setLoading(false);
}
}
};
const unsubscribe = dynamicLinks().onLink(handleDynamicLink);
/* When the app is not running and is launched by a magic link the `onLink`
method won't fire, we can handle the app being launched by a magic link like this */
dynamicLinks().getInitialLink()
.then(link => link && handleDynamicLink(link));
// When the component is unmounted, remove the listener
return () => unsubscribe();
}, []);
return { error, loading };
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFill,
backgroundColor: 'rgba(250,250,250,0.33)',
justifyContent: 'center',
alignItems: 'center',
},
});
const App = () => (
<View>
<EmailLinkHandler />
<AppScreens />
</View>
);
You can use the component in the root of your app as in this example
Or you can use it as a separate screen/route - in that case the user should be redirected to it after
the sendSignInLinkToEmail action
Upon successful sign-in, any onAuthStateChanged listeners will trigger with the new authentication state of the user. The result from the signInWithEmailLink can also be used to retrieve information about the user that signed in
Testing the email login link in the simulator
Have the app installed on the running simulator
Go through the flow that will send the magic link to the email
Go to your inbox and copy the link address
Open a terminal and paste the following code
xcrun simctl openurl booted {paste_the_link_here}
This will start the app if it’s not running
It will trigger the onLink hook (if you have a listener for it like above)
References
Deep Linking In React Native Using Firebase Dynamic Links
React Native Firebase - Dynamic Links
React Native Firebase - auth - signInWithEmailLink
firebase.google.com - Passing State In Email Actions
firebase.google.com - Authenticate with Firebase Using Email Link in JavaScript

TypeError Object is not a constructor (evaluating new_pubnubReact.default')

I am new to react native and am trying to create push notifications for android.
I am using the following tutorial from PubNub.
PubNub tutorial
When I run my app in the android studio emulator after finishing the tutorial I get the following error.
Not quite sure what it means of how to fix it as when I google the problem nothing comes up.
Here is my code
import React from 'react';
import PushNotificationIOS from 'react-native';
import PubNubReact from 'pubnub-react';
const PushNotification = require('react-native-push-notification');
export default class App extends React.Component {
constructor(props) {
super(props);
this.pubnub = new PubNubReact({
publishKey: 'YOUR_PUBNUB_PUBLISH_KEY_HERE',
subscribeKey: 'YOUR_PUBNUB_SUBSCRIBE_KEY_HERE'
});
this.pubnub.init(this);
PushNotification.configure({
// Called when Token is generated.
onRegister: function(token) {
console.log( 'TOKEN:', token );
if (token.os == "ios") {
this.pubnub.push.addChannels(
{
channels: ['notifications'],
device: token.token,
pushGateway: 'apns'
});
// Send iOS Notification from debug console: {"pn_apns":{"aps":{"alert":"Hello World."}}}
} else if (token.os == "android"){
this.pubnub.push.addChannels(
{
channels: ['notifications'],
device: token.token,
pushGateway: 'gcm' // apns, gcm, mpns
});
// Send Android Notification from debug console: {"pn_gcm":{"data":{"message":"Hello World."}}}
}
}.bind(this),
// Something not working?
// See: https://support.pubnub.com/support/solutions/articles/14000043605-how-can-i-troubleshoot-my-push-notification-issues-
// Called when a remote or local notification is opened or received.
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
// Do something with the notification.
// Required on iOS only (see fetchCompletionHandler docs: https://reactnative.dev/docs/pushnotificationios)
// notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// ANDROID: GCM or FCM Sender ID
senderID: "sender-id",
});
}
}
pubnub-react library has been completely changed in version 2.0.0. It no longers includes pubnub JavaScript SDK by default so you have to install it as well.
Here is the link to new PubNub React repository, and in the README.md file you can find examples on how to use it.
If you want to use the older version that is compatible with the tutorial/blog post you may be reading, please install the older version of the PubNub React SDK like so:
$ npm install pubnub-react#1
To summarize the changes, pubnub-react now uses Context and Hooks API to propagate PubNub instance deep into the children tree.
Provider
You need to include the provider somewhere top in the component tree.
import React from 'react'
import PubNub from 'pubnub'
import { PubNubProvider } from 'pubnub-react'
const pubnub = new PubNub({}) // PubNub configuration
export const App = () => {
return <PubNubProvider client={pubnub}>
<Child />
</PubNubProvider>
}
Consumer
To use the PubNub instance somewhere else, you can now just use the usePubNub hook.
import { usePubNub } from 'pubnub-react'
export const Child = () => {
const pubnub = usePubNub()
return <div>I am using PubNub!</div>
}

React native local notifications

I am new to React Native and need to implement a functionality where the app needs to send the user a notification every day at a certain time. The data to be shown for each day is stored in a json file on the client side and will not change. The notifications are on a schedule. Given that I was hoping there could be a way to just trigger a notification from the app itself.
Does anyone know of a way to achieve this without having to detach the app from expo? I can't use 'react-native-push-notification'without running react-native link and that requires me to detach the app. Is that right?
Is this possible?
Thanks :)
You can do this with expo using the scheduleLocalNotificationAsync function (have a look at these docs for more details). Make sure you have permission to send notifications first. Note that if the notification triggers when the app is in the foreground you won't see a notification but you can still listen to this event.
i. Ask for permission
import { Permissions } from 'expo';
// ... somewhere before scheduling notifications ...
const { status } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
if (status !== 'granted') {
await Permissions.askAsync(Permissions.NOTIFICATIONS);
}
ii. Schedule the notification
import { Notifications } from 'expo';
const notification = {
title: 'Hi there!',
body: 'Tap me to open the app.',
android: { sound: true }, // Make a sound on Android
ios: { sound: true }, // Make a sound on iOS
};
const options = {
time: Date.now() + 10000, // Schedule it in 10 seconds
repeat: 'day', // Repeat it daily
};
// ... somewhere after requesting permission ...
const id = Notifications.scheduleLocalNotificationAsync(notification, options)
// If you want to react even when your app is still in the
// foreground, you can listen to the event like this:
Notifications.addListener(() => {
console.log('triggered!');
});
iii. Cancel the scheduled notification
You can use the returned id of the scheduleLocalNotificationAsync function to cancel the notification.
import { Notifications } from 'expo';
// ... get the id of the scheduled notification ...
Notifications.cancelScheduledNotificationAsync(id)

How to pass data to push notification with react native

Im using
React Native Push Notification https://github.com/zo0r/react-native-push-notification
How can I pass my pushMessage(chat) into the notification?
I have this onNotification and PushNotificationIOS error when received push message from server.
error on device
which part should I work on?
ps: im not understand how this work -> notification.finish(PushNotificationIOS.FetchResult.NoData);
App.js
--------
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
// process the notification
// required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
});
class App extends Component{
componentDidMount(){
const connection = signalr.hubConnection('https://api.abc.com');
const proxy = connection.createHubProxy('chatHub');
proxy.on('pushMessage', (chat) => {
PushNotification.localNotificationSchedule({
message: "My Notification 1",
date: new Date(Date.now())
});
});
}
}
PushNotificationIOS is an API provided by react-native so maybe you import it from react-native like so
import { PushNotificationIOS } from 'react-native'
PushNotification uses PushNotificationIOS. You have to add and import it.
Do the following.
In the console, run this if using Yarn: yarn add #react-native-community/push-notification-ios...
... or run this if using NPM: npm install #react-native-community/push-notification-ios
Then, in your file where you use PushNotification, add this line among your other imports:
import PushNotificationIOS from "#react-native-community/push-notification-ios"