如何阅读firebase推送通知内容并在ionic2中触发方法

如何阅读firebase推送通知内容并在ionic2中触发方法

本文介绍了如何阅读firebase推送通知内容并在ionic2中触发方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 ionic 2 中访问 push notification 内容并在通知到达或 event fire 时执行一堆代码?

解决方案

我推荐使用

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

解决方案

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

这篇关于如何阅读firebase推送通知内容并在ionic2中触发方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 15:52