How to read firebase push notification content and

2019-04-15 01:23发布

Is it possible to access push notification content in ionic 2 and execute bunch of code when notification arrive or event fire?

2条回答
我想做一个坏孩纸
2楼-- · 2019-04-15 01:32

Yes it is, you'll need a plugin to this, i use the cordova-plugin-fcm.

In your app.ts you can do the following

declare var FCMPlugin: any; //declare with the imports

FCMPlugin.onNotification(function(data){
  if(data.wasTapped){
    //Notification was received on device tray and tapped by the user.
    alert( JSON.stringify(data) );
  }else{
    //Notification was received in foreground. Maybe the user needs to be notified.
    alert( JSON.stringify(data) );
  }
});

Inside was tapper you'll do your code.

Hope this helps.

查看更多
够拽才男人
3楼-- · 2019-04-15 01:50

I'd recommend using the cordova-plugin-firebase instead. You can take a look at this repo to see how to use that plugin.

Please notice that you'd need first to configure the firebase console, and donwload the .json / .plist files and add them to the root folder of your Ionic app. Then you can start using the plugin.

In the demo everything is done in the app.component.ts file, but I recommend creating a PushNotificationService to keep everything organised.

Please also notice that the demo uses topics features, so devices can subscribe to specific topics, and then we can use these topics to send notifications to some group of users (only android or ios, only a specific user, all users from the app...):

this.firebase.subscribe('firebase-app'),    // Subscribe to the entire app
this.firebase.subscribe('android'),         // Subscribe to android users topic
this.firebase.subscribe('userid-1')         // Subscribe using the user id (hardcoded in this example)

This is all the related code:

// Angular
import { Component } from '@angular/core';

// Ionic
import { Platform, AlertController } from 'ionic-angular';

// Ionic Native
import { Firebase } from '@ionic-native/firebase';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

// Pages
import { HomePage } from '../pages/home/home';

export class NotificationModel {
    public body: string;
    public title: string;
    public tap: boolean
}

@Component({
    templateUrl: 'app.html'
})
export class MyApp {
    rootPage: any = HomePage;

    constructor(private platform: Platform,
        private alertCtrl: AlertController,
        private firebase: Firebase,
        private statusBar: StatusBar,
        private splashScreen: SplashScreen) {

        this.platform.ready().then(() => {
            this.statusBar.styleDefault();
            this.splashScreen.hide();

            if (this.platform.is('cordova')) {
                // Initialize push notification feature
                this.platform.is('android') ? this.initializeFireBaseAndroid() : this.initializeFireBaseIos();
            } else {
                console.log('Push notifications are not enabled since this is not a real device');
            }
        });
    }

    private initializeFireBaseAndroid(): Promise<any> {
        return this.firebase.getToken()
            .catch(error => console.error('Error getting token', error))
            .then(token => {

                console.log(`The token is ${token}`);

                Promise.all([
                    this.firebase.subscribe('firebase-app'),    // Subscribe to the entire app
                    this.firebase.subscribe('android'),         // Subscribe to android users topic
                    this.firebase.subscribe('userid-1')         // Subscribe using the user id (hardcoded in this example)
                ]).then((result) => {
                    if (result[0]) console.log(`Subscribed to FirebaseDemo`);
                    if (result[1]) console.log(`Subscribed to Android`);
                    if (result[2]) console.log(`Subscribed as User`);

                    this.subscribeToPushNotificationEvents();
                });
            });
    }

    private initializeFireBaseIos(): Promise<any> {
        return this.firebase.grantPermission()
            .catch(error => console.error('Error getting permission', error))
            .then(() => {
                this.firebase.getToken()
                    .catch(error => console.error('Error getting token', error))
                    .then(token => {

                        console.log(`The token is ${token}`);

                        Promise.all([
                            this.firebase.subscribe('firebase-app'),
                            this.firebase.subscribe('ios'),
                            this.firebase.subscribe('userid-2')
                        ]).then((result) => {

                            if (result[0]) console.log(`Subscribed to FirebaseDemo`);
                            if (result[1]) console.log(`Subscribed to iOS`);
                            if (result[2]) console.log(`Subscribed as User`);

                            this.subscribeToPushNotificationEvents();
                        });
                    });
            })

    }

    private saveToken(token: any): Promise<any> {
        // Send the token to the server
        console.log('Sending token to the server...');
        return Promise.resolve(true);
    }

    private subscribeToPushNotificationEvents(): void {

        // Handle token refresh
        this.firebase.onTokenRefresh().subscribe(
            token => {
                console.log(`The new token is ${token}`);
                this.saveToken(token);
            },
            error => {
                console.error('Error refreshing token', error);
            });

        // Handle incoming notifications
        this.firebase.onNotificationOpen().subscribe(
            (notification: NotificationModel) => {

                !notification.tap
                    ? console.log('The user was using the app when the notification arrived...')
                    : console.log('The app was closed when the notification arrived...');

                let notificationAlert = this.alertCtrl.create({
                    title: notification.title,
                    message: notification.body,
                    buttons: ['Ok']
                });
                notificationAlert.present();
            },
            error => {
                console.error('Error getting the notification', error);
            });
    }
}

Also please notice, that the content of the notification sent will not be the same if the app is running in the foreground or if the app is closed when the notification arrives. In order to handle that, when sending a notification, add the title and the body in the Advanced options section

Example

查看更多
登录 后发表回答