ionic 3 - receive Push notifications on Ionic dont work - firebase

Has anyone worked with notifications on ionic 3? I'm trying to create some apps that store fcm notification, I'm trying most of the tutorials out there but nothing seems working. When I get notification and tap it, I can't get the message.
Here's some code that I've tried
initializeApp() {
this.platform.ready().then(() => {
// START
this.fcm.getToken().then(token => {
console.log(token);
alert('token: '+token);
});
this.fcm.onTokenRefresh().subscribe(token => {
console.log(token);
alert('refresh token: '+token);
});
this.fcm.onNotification().subscribe(data => {
alert('data: '+data);
if(data.wasTapped){
console.log("Received in background " + JSON.stringify(data) );
alert("Received in background " + JSON.stringify(data) );
this.nav.setRoot(InboxnotifPage, {data: data});
} else {
console.log("Received in foreground" + JSON.stringify(data) );
alert("Received in foreground" + JSON.stringify(data) );
this.nav.push(InboxnotifPage, {data: data});
};
});
// END
}
}

you have to add .plist file in your project build root to communicate with your device
this.fcm.onNotification().subscribe(data => {
if (data.wasTapped) {
alert('');
} else {
console.log("Received in foreground");
// this.presentToast("Received in foreground");
}
});
this.getToken();
this.fcm.onTokenRefresh().subscribe(token => {
this.rest.globalToken = token;
});
});
follow the original documentation and please first of all check notification from https://console.firebase.google.com then pass token to rest Api

Related

React native cannot receive notification using firecloud Messaging in ios

I need your help, all looks good but I cannot receive notification on my react-native application.
Actual setup:
In project.xcworkspace, TARGETS > {App Name} > Signing & Capabilities :
Background Modes: Background fetch and Remote notifications enabled
Push Notifications
Firebase Project:
APNs key was added, with KeyId, TeamId
Apple Developer:
Identifier added with Push Notifications enabled
Key added with "Apple Push Notifications service (APNs)"
Profiles > I created a "Provisioning Profile" to try if I have a connection issue(not resolved with this)
Good to know: I actually use the firebase authentification and it works so I don't think it's a GoogleService-Info.plist issue.
App.js
const requestNotificationPermission = async () => {
messaging()
.requestPermission()
.then(authStatus => {
console.log('APNs Status: ', authStatus);
if (
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus == messaging.AuthorizationStatus.PROVISIONAL
) {
messaging()
.getToken()
.then(async (token) => {
await messaging().registerDeviceForRemoteMessages()
.then((result) => {
console.log('Device registered for remote messages: ', result);
});
console.log('Token', token);
});
messaging().onTokenRefresh(token => {
console.log('Refresh Token: ', token)
});
}
})
.catch(err => {
console.log('Error: ', err);
});
}
React.useEffect(() => {
requestNotificationPermission();
const unsubscribe = messaging().onMessage(async remoteMessage => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
})
return unsubscribe;
}, [])
Return :
LOG APNs Status: 1
LOG Device registered for remote messages: true
LOG Token fmORQaQ0FUCjnGA1TgXSDi:APA91bFVDMvgkY13Rl-muzI2kOKCJauFcJCVF7sZZxgnuicawTIcvrl73JtNUEruobDfu1igvgVkXobi3gUTvGXD1QMZoOskXUzAEkDJpMgUvug-9KudE6bJl9oBL0tJCc9Eqv0GXfXa
I tried to create a notification from https://console.firebase.google.com/u/0/project/proj-number/messaging
Result: Nothing append on react-native app.
I tried to create a notification from REST
REST Request Setup :
Method: POST
Url : https://fcm.googleapis.com/fcm/send
Headers > Authorization > key={Cloud Messaging > Server Key}
Body :
{
"data": {},
"notification": {
"body": "This is an FCM notification",
"title": "From Postman"
},
"to": "fmORQaQ0FUCjnGA1TgX[...]"
}
Postman Result :
{
"multicast_id": 5211676236934629976,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1660579924324918%fedf4cbefedf4cbe"
}
]
}
React-native result : Nothing append on react-native app.
Resolved:
App.js
const getToken = () => {
messaging()
.getToken()
.then(x => console.log(x))
.catch(e => console.log(e));
};
const registerForRemoteMessages = () => {
messaging()
.registerDeviceForRemoteMessages()
.then(() => {
console.log('Registered');
requestPermissions();
})
.catch(e => console.log(e));
};
const requestPermissions = () => {
messaging()
.requestPermission()
.then((status) => {
if (status === 1) {
console.log('Authorized');
onMessage();
} else {
console.log('Not authorized');
}
})
.catch(e => console.log(e));
};
const onMessage = () => {
messaging()
.onMessage(response => {
console.log(response.data.notification);
});
};
React.useEffect(() => {
getToken();
if (Platform.OS === 'ios') {
registerForRemoteMessages();
} else {
onMessage();
}
const unsubscribe = messaging().onMessage(async remoteMessage => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
})
return unsubscribe;
}, [])

Notification via rest api in react native

I am trying to send notification in react native via rest api. In response i'm getting success :1. The problem here is i'm not getting notification in emulator.
const token = await firebase.messaging().getToken();
console.log("token in sendNotification ",token)
const FIREBASE_API_KEY = "firebaseApiKey";
const message = {
to :token,
notification: {
title: "This is a Notification",
boby: "This is the body of the Notification",
vibrate: 1,
sound: 1,
show_in_foreground: true,
priority: "high",
content_available: true,
}
}
let headers = new Headers({
"Content-Type" : "application/json",
Authorization: "key=" + FIREBASE_API_KEY,
})
try {
let response = await fetch ("https://fcm.googleapis.com/fcm/send",{
method: "POST",
headers,
body: JSON.stringify(message),
})
response = await response.json();
console.log("response ", response);
} catch (error) {
console.log("error ", error);
}
https://firebase.google.com/docs/cloud-messaging/js/receive
You can follow the incoming message documentation
// Handle incoming messages. Called when:
// - a message is received while the app has a focus
// - the user clicks on an app notification created by a service worker
// `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// ...
});
In useEffect of App.js
import React,{useEffect} from 'react'
import{View,Text} from 'react-native';
async function onDisplayNotification() {
// Create a channel
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
});
// Display a notification
await notifee.displayNotification({
title: 'Notification Title',
body: 'Main body content of the notification',
android: {
channelId,
smallIcon: 'ic_launcher', // optional, defaults to 'ic_launcher'.
},
});
}
const App=()=> {
useEffect(() => {
// Assume a message-notification contains a "type" property in the data payload of the screen to open
messaging().onMessage((payload) => {
console.log('Message received. ', payload);
onDisplayNotification();
// ...
});
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
alert("Notification");
});
// Check whether an initial notification is available
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
}
});
}, []);
return (
<View>
</View>
)
}
export default App;

RNFirebase v6 Push Notifications are not coming both iOS&Android

I am trying to send notifications from firebase console to my react-native app
I followed the poor documentation here as much as I understand: https://invertase.io/oss/react-native-firebase/v6/messaging/quick-start
I installed #react-native-firebase/app and /messaging and here is my code in component:
componentDidMount() {
this.reqNotifications()
this.checkNotificationPermission()
}
reqNotifications() {
requestNotifications(['alert', 'badge', 'sound']).then(({status, settings}) => {
console.log('NOTIFICATION STATUS' + status)
});
}
async checkNotificationPermission() {
const enabled = await messaging().hasPermission();
if (enabled) {
console.log('APPROVED');
await messaging().registerForRemoteNotifications()
messaging().getToken().then(token => console.log('token: >> ' + token))
} else {
console.log('NOT APPROVED');
}
}
I am requesting permission via react-native-permissions and permission request is
working.
My Apple APNs are OK on Apple and Firebase console
And I am getting my token by getToken() method on the code
succesfully.
But I cant send anything to device from firebase; nothing happening on neither foreground nor background . I tried with-token test and also tried normal but no, nothing happens.
I added this code to componentDidMount:
messaging().onMessage(async remoteMessage => {
console.log('FCM Message Data:', remoteMessage.data);
});
As I understand this subscribes for cloud messages and when I send some cloud message notification from firebase-console, I should get console output; but nothing happens.
I dont know what am I missing but I think there is a big update on this package and most of docs are for previous version and I really stuck here thanks for assist
for rnfirebase.io V6
componentDidMount = async () => {
this.checkNotificationPermission();
await messaging().requestPermission({provisional: true});
await messaging().registerDeviceForRemoteMessages();
await this.getFCMToken();
if (Platform.OS === 'android') {
this.createAndroidNotificationChannel();
}
this.backgroundState();
this.foregroundState();
};
checkNotificationPermission = () => {
firebase
.messaging()
.hasPermission()
.then(enabled => {
if (!enabled) {
this.promptForNotificationPermission();
}
});
};
promptForNotificationPermission = () => {
firebase
.messaging()
.requestPermission({provisional: true})
.then(() => {
console.log('Permission granted.');
})
.catch(() => {
console.log('Permission rejected.');
});
};
createAndroidNotificationChannel() {
const channel = new firebase.notifications.Android.Channel(
'channelId',
'Push Notification',
firebase.notifications.Android.Importance.Max,
).setDescription('Turn on to receive push notification');
firebase.notifications().android.createChannel(channel);
}
foregroundState = () => {
const unsubscribe = messaging().onMessage(async notification => {
console.log('Message handled in the foregroundState!', notification);
});
return unsubscribe;
};
// Register background handler
backgroundState = () => {
messaging().setBackgroundMessageHandler(async notification => {
console.log('Message handled in the background!', notification);
});
};

Nativescript with Firebase : Works login in offline mode

I use nativescript-plugin-firebase to connect with Firebase. It does work when create new user / login / CRUD operations when app is online mode.
When the app is offline mode, Login authentication / Create new user is not working rest of the above mentioned things are working.
My code base:
app.component.ts
ngOnInit(): void {
firebase.init({
persist: true,
storageBucket: 'gs://**************/',
onAuthStateChanged: (data: any) => {
console.log(JSON.stringify(data))
if (data.loggedIn) {
BackendService.token = data.user.uid;
}
else {
BackendService.token = "";
}
}
}).then(
function (instance) {
console.log("firebase.init done");
},
function (error) {
console.log("firebase.init error: " + error);
}
);
firebase.keepInSync(
"/users", // which path in your Firebase needs to be kept in sync?
true // set to false to disable this feature again
).then(
function () {
console.log("firebase.keepInSync is ON for /users");
},
function (error) {
console.log("firebase.keepInSync error: " + error);
}
);
in service file
login(user: User) {
return firebase.login({
type: firebase.LoginType.PASSWORD,
email: user.email,
password: user.password
}).then((result: any) => {
BackendService.token = result.uid;
return JSON.stringify(result);
}, (errorMessage: any) => {
// alert(errorMessage);
alert('Email address / Password is wrong!!!');
});
}
Anyone help me how login will work in when offline mode.

Nativescript firebase vibration when app in background

When app in background, firebase plugin not calling onMassageReceived and I can't add vibration, when notification received. How I can solve that?
import firebase = require("nativescript-plugin-firebase");
var vibrator = require("nativescript-vibrate");
firebase.init({
url: AppUrl
}).then(
(instance) => {
console.log("firebase.init done true");
},
(error) => {
console.log("firebase.init error: " + error);
}
);
firebase.addOnMessageReceivedCallback((message:any)=>{
vibrator.vibration(500);
});

Resources