Calling showNotification does not show anything special - push-notification

I would like to implement Google's Push Notification in a website and followed this tutorial by Google:
https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications
I managed to display a Push Notification and the permission status in the Console but got stuck with the stage where the showNotification method is used to bring up a message.
My code goes as follows:
Notification.requestPermission(status => {
console.log('Notification permission status:', status);
});
function displayNotification() {
if (Notification.permission == 'granted') {
navigator.serviceWorker.getRegistration().then(function(reg) {
reg.showNotification('Hello world!');
});
}
}
I browsed the videos and labs to no avail. They simply use the code stated above or similar with with the optional array incorporated.
Please help me work out how calling the showNotification method can modify the Push Notification.

Related

How can I access title and body data from pushNotificationActionPerformed into the ionic application with capacitor

I'm using Capacitor Push Notifications into my app. I've follow the capacitor tutorial from capacitor website, and implemented this code:
onPushNotifications() {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
// On succcess, we should be able to receive notifications
PushNotifications.addListener('registration', (token: PushNotificationToken) => {
console.log('Push registration success, token: ' + token.value);
});
// Some issue with our setup and push will not work
PushNotifications.addListener('registrationError', (error: any) => {
console.log('Error on registration: ' + JSON.stringify(error));
this.showToast('Erro ao ativar as notificações push.');
});
// Show us the notification payload if the app is open on our device
PushNotifications.addListener('pushNotificationReceived', (notification: PushNotification) => {
this.showToast(notification.title + '\n' + notification.body);
this.addNewNotification(notification);
});
// Method called when tapping on a notification
PushNotifications.addListener('pushNotificationActionPerformed', (notification: PushNotificationActionPerformed) => {
this.addNewNotification(notification.notification.data);
});
}
With this, I could access data title and body from push notification when the app is running in foreground (using pushNotificationReceived). But when the app is running in background I could access the title and body to save in an array, for exemple.
I tried implement this code:
// Method called when tapping on a notification
PushNotifications.addListener('pushNotificationActionPerformed',
(notification: PushNotificationActionPerformed) => {
let notif = this.state.notifications;
notif.push({ id: notification.notification.data.id, title: notification.notification.data.title, body: notification.notification.data.body })
this.setState({
notifications: notif
})
}
);
From this website https://medium.com/enappd/firebase-push-notification-in-ionic-react-app-using-capacitor-b6726c71bda4
But I got no functional answer. I keep getting undefined in title and body.
Please, can someone help me?
Thanks!
Your payload should contain:
notification_foreground,
notification_title,
notification_body.
You have to make:
notification_foreground = true
Sadly that’s how push with notification payload work, when in background or closed the OS handles them, using the title and body to display the notification in the tray, but when you tap them, that information is no longer available for the app.
Use data payload to pass any data you want.

some codes don't work. i dont know why. how can i make the codes work?

I wanna make Login screen in unity. I'm gonna use firebase, and followed the manual in firebase page and some youtube channel to learn how to use firebase.
and.. some codes don't work. I used the codes that firebase give, and the codes that are below login success don't work. um.. sorry for my weak English. please see the codes. thanks.
this codes don't work
authUI.ShowLoggedInPanel();// 로그인 성공 시 메인메뉴로 전환!
authUI.LoggedInUserEmail.text = newUser.Email;
I don't know what i can try..
private void TryLoginWithFirebaseAuth(string email, string password) // 기존 사용자 로그인
{
auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task =>
{
if (task.IsCanceled)
{
Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
// 로그인 성공 (Maybe Login success?)
Firebase.Auth.FirebaseUser newUser = task.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})",
newUser.DisplayName, newUser.UserId);
authUI.ShowLoggedInPanel();// 로그인 성공 시 메인메뉴로 전환!
authUI.LoggedInUserEmail.text = newUser.Email;
});
}
It doesn't show the error to me. but just.. it doesn't work.
Could someone help me out here.
I don't know Firebase well but the issue might be the threading.
All (the most) Unity API calls have to be done in the main thread. Since Firebase executes its stuff async in a background thread some calls might simply fail.
You should rather use an Action parameter in order to pass a callback to the method like e.g.
private void TryLoginWithFirebaseAuth(string email, string password, Action<Firebase.Auth.FirebaseUser> successCallback) // 기존 사용자 로그인
{
auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task =>
{
if (task.IsCanceled)
{
Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
// 로그인 성공 (Maybe Login success?)
Firebase.Auth.FirebaseUser newUser = task.Result;
successCallback?Invoke(newUser);
});
}
and use it like
TryLoginWithFirebaseAuth(someName, somePassword, onSuccess =>
{
Debug.LogFormat("User signed in successfully: {0} ({1})",
onSuccess.DisplayName, onSuccess.UserId);
authUI.ShowLoggedInPanel();// 로그인 성공 시 메인메뉴로 전환!
authUI.LoggedInUserEmail.text = onSuccess.Email;
}
this makes sure it is definitely executed in the Unity main thread.
It's hard to definitely answer your question without more context around it (ex: are there any useful logs in the Unity console?).
Some things to note:
You have to make sure you've setup Authentication in the Firebase Console. This means clicking Authentication in your side bar and explicitly enabling the methods you want:
Similarly, you need to make sure that your applications are properly setup. Your package id/bundle id (Android/iOS) need to match what's in your console. Similarly, you need to upload the SHA1 of your signing certificate to get it to work in Android.
I'm assuming that you're just debugging for now, so you can get your debug certificate here: https://developers.google.com/android/guides/client-auth
You'll want to open up project settings:
And add your fingerprint there:
Following up on #derHugo's suggest, threading may be an issue in addition to the basic setup instructions above. I wrote a post recently on how to work with threading and Firebase in Unity here: https://firebase.googleblog.com/2019/07/firebase-and-tasks-how-to-deal-with.html
The easiest way to make your code thread safe would be to replace ContinueWith with ContinueWithOnMainThread. This is an extension method on Task provided by the Firebase plugin to make it easier to work with.
I hope that all helps!
This is a classic Task continuation problem in Unity using Firebase. When you use, ContinueWith it is not ensured to be called on the main Unity thread. What you're trying to do authUI.ShowLoggedInPanel();authUI.LoggedInUserEmail.text = newUser.Email; requires to be executed on the Unity main thread. If you try to access GameObjects inside ContinueWith, that will fail. The code just ghosts out without any error in the console.
The solution:
Instead of ContinueWith, use ContinueWithOnMainThread from Firebase extensions which was made exactly for this reason.

Save device token with FCM in ionic 2

I am using FCM plugin to do push notification for ionic2.
reference : https://www.npmjs.com/package/cordova-plugin-fcm
I followed https://github.com/edismooth/ionic2-firebase/tree/master
It works fine and I can received the push from firebase console. Now I want to build my own server to let admin to send push notification with own backend.
I faced one problem is : I can get the device token, however, I have no idea how to save it to local storage. The code is as below. May I know which part I am wrong? Is that “this.local.set” can’t be used within the function of “FCMPlugin.getToken”. If yes, how can I save the token and use out of this function? Many thanks.
initializeApp() {
this.platform.ready().then(() => {
StatusBar.styleDefault();
FCMPlugin.getToken(
function (token) {
console.log(token); //I can get the token data
this.local.set('tokenvalue', token); // the token value can't be saved to local storage like this
},
function (err) {
console.log('error retrieving token: ' + err);
}
);
}
First, try this this.localStorage.set(...), if that doesn't work and you have access to the window object. Use window.localStorage.setItem(...)
You can use ionic Storage.
I describe it in this answer.
https://stackoverflow.com/a/41105221/902630

How do I use Meteor and a Cordova BLE plugin to connect to a BLE device

I'm trying to use Meteor and this Cordova plugin -https://github.com/don/cordova-plugin-ble-central - added to my project using meteor add cordova in order to connect to a Bluetooth LE device (TI Sensortag). All I want to do to begin with is, when a link is clicked, to connect to the device and show a message.
I have the following code in the events section of my template javascript.
Template.measure.events({'click [data-action=scan-connect-stream]':
function(event, template) {
event.preventDefault();
if (Meteor.isCordova) {
Meteor.startup(function () {
ble.connect('24:09:00:DE:00:42',
function(){
alert('Connect success');
return;
},
function(){
alert('Connect failed');
return;
});
});
}
}
});
My problem is that sometimes the code works and I get a 'Connect success' alert but more often than not it it fails to connect and shows the 'Connect failed' alert. Before I added the return statements in the success and fail callbacks it didn't work at all.
I'm debugging this on an android device (meteor run android-device --verbose) and can see via adb logcat that the BLE Connect event in the Cordova plugin is firing but then doesn't connect. I get the same issue debugging on two different phones and when using a BLE device that isn't a TI Sensortag so I'm guessing this is an problem with the way the plugin is interacting with Meteor (maybe Meteor isn't waiting long enough for a success callback?).
Has anyone used this plugin successfully with Meteor or can anyone provide any clue as to what I'm doing wrong? Should I try wrapping it in a Meteor package or is there any way I can give the plugin more time to respond before the success or fail callbacks fire? Any help would be much appreciated!
For anyone who's having similar issues this is what sorted it for me. I put the ble.connect call into the success callback of the ble.scan function. Not sure why but scanning for a few seconds first does the job.
Template.measure.events({
'click [data-action=scan-connect-stream]': function(event, template) {
event.preventDefault();
if (Meteor.isCordova) {
Meteor.startup(function () {
device_id = '24:09:00:DE:00:42';
ble.scan([], 5,
function(peripherals){
connectDevice(device_id);
},
function(){
alert('No devices found');
}
);
});
}
}
});
var connectDevice = function (device_id) {
ble.connect(device_id,
function(){
alert('Device ' + device_id + ' connnected');
},
function(){
alert('Couldn\'t connect to device ' + device_id);
});
}
If anyone can explain why the ble.connect won't work on its own that'd be great!
EDIT: Looking at the Android code it seems that the plugin is designed in such a way that ble.scan has to be called before calling ble.connect. The ble.scan causes a LinkedHashMap in the Android code to be populated with any discovered devices. Only once the device is listed in the LinkedHashMap can you then connect to it using ble.connect.

ngCordova/Ionic Push Notifications when application is in the background

I'm currently building an android application using ionic/ngcordova. I'm at the point of implementing push notifications. I've implemented push notifications as a service which is injected at app.run(function(){..}) stage. The registration part works and I receive a callback containing the regid. Also, when the application is in the active state, the event is raised and the notification is received.
The problem I'm having is that when the application goes into the background, the notifications are not received at all. I would expect that a local notification would be raised when the app isn't running or something similar, but absolutely nothing happens, which is weird.
I've trawled the web for the last couple of days looking for a solution but I've been unable to find anything which kind of indicates to me that it should just work.
The following is my notificationService.js inside my app
app.factory('notificationService', ['$cordovaPush', function($cordovaPush){
var dataFactory = {};
//
// When the device is ready and this service has been plumbed in...
document.addEventListener("deviceready", function(){
console.log("initializing push notifications...");
_register();
}, false);
//
// Registers the device for push notifications...
var _register = function(){
var config = {};
if ( device.platform == 'android' || device.platform == 'Android' || device.platform == "amazon-fireos" ){
// TODO: centralise this value as it can change...
config = {
senderID: "448168747432",
ecb: "onNotificationGCM"
};
}else {
// iOS
config = {
"badge":"true",
"sound":"true",
"alert":"true"
};
// Can add the following property to the config object to raise a callback with the information if need be...
// "ecb": "onNotificationRegisterAPN"
}
$cordovaPush.register(config).then(function(result){
//
// Typically returns "ok" for android and devicetoken for iOS
console.log(result);
});
};
window.onNotificationGCM = function(result){
console.log(result);
/*
I get called when the app is in the foreground, but nothing happens when the app is in the background.
*/
};
dataFactory.register = _register;
return dataFactory;
}]);
If it helps, I'm using PushSharp via a .net application in order to deliver the notifications. Any help would be greatly appreciated.
UPDATE: I'm using the following frameworks/libs:
Ionic Framework 1.2.14-beta6
Cordova 4.2.0
PushPlugin
For anyone else who's been pulling their hair out for a couple of days like I have, the solution was really simple...I was missing two properties in my Pushsharp QueueNotification request. So using the example given on the PushSharp github repo here: https://github.com/Redth/PushSharp#sample-code
push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("DEVICE-REGISTRATION-ID-HERE").WithJson("{\"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}"));
Needs to be updated to add the missing properties:
push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("DEVICE REGISTRATION ID HERE")
.WithJson(#"{""alert"":""This is the future"",""badge"":7,""sound"":""sound.caf"",""title"":""Status Bar title"",""message"":""Some text you want to display to the user""}"));
Otherwise if your app happens to be developed using Cordova and its not currently in the foreground, nothing, repeat nothing will happen.
Tip my hat to gdelavald with his comment on PushPlugin for pointing me in the right direction here:
https://github.com/phonegap-build/PushPlugin/issues/212

Resources