Ionic + Firebase - Push notifications

2019-08-30 01:29发布

问题:

I have a ionic + firebase chat app and I'd like to send a notification to a user when a new message is received.

In the Ionic oficial documentation, the recommended plugin for this is: https://github.com/katzer/cordova-plugin-local-notifications

But as you can see inside the repository, it hasnt been updated since last february and based in comments inside it, it seems like it doesnt work with last Android OS versions.

Does anyone know an alternative?

Thanks!

回答1:

I had the same problem to implement push notifications in my app last month. This is the best tutorial to do that: https://medium.com/@senning/push-notifications-with-ionic-and-cordova-plugin-firebase-ab0c0cad3cc0

I customized this tutorial to a file: messaging.service.ts

import {Injectable} from '@angular/core';
import {ApiService} from './api.service';
import {AppApiResponse} from '../interfaces/interfaces'
import {Firebase} from "@ionic-native/firebase";
import {Platform} from "ionic-angular";
import {AngularFirestore} from "@angular/fire/firestore";

@Injectable()
export class MessagingService {

  private userUid: string;

  constructor(private firebase: Firebase,
              public afs: AngularFirestore,
              public platform: Platform) {
  }

  initializeFirebase(userUid) {
    this.userUid = userUid;
    if (!this.platform.is("core")) {
      this.firebase.subscribe("all");
      this.platform.is('android') ? this.initializeFirebaseAndroid() : this.initializeFirebaseIOS();
    }
  }

  initializeFirebaseAndroid() {
    this.firebase.getToken().then(token => {
      this.saveTokenToFirestore(token);
      console.log('token android= ' + JSON.stringify(token));
    });
    this.firebase.onTokenRefresh().subscribe(token => {
      this.saveTokenToFirestore(token);
      console.log('token refresh android= ' + JSON.stringify(token));
    });
    this.subscribeToPushNotifications();
  }

  initializeFirebaseIOS() {
    this.firebase.grantPermission()
      .then(() => {
        this.firebase.getToken().then(token => {
          this.saveTokenToFirestore(token);
          console.log('token ios= ' + JSON.stringify(token));
        });
        this.firebase.onTokenRefresh().subscribe(token => {
          this.saveTokenToFirestore(token);
          console.log('token refresh ios= ' + JSON.stringify(token));
        });
        this.subscribeToPushNotifications();
      })
      .catch((error) => {
        this.firebase.logError('push erro ios= ' + error);
      });
  }

  subscribeToPushNotifications() {
    this.firebase.onNotificationOpen().subscribe((response) => {
      console.log('response push= ' + JSON.stringify(response));
      if (response.tap) {
        //Received while app in background (this should be the callback when a system notification is tapped)
        //This is empty for our app since we just needed the notification to open the app
      } else {
        //received while app in foreground (show a toast)
      }
    });
  }

  private saveTokenToFirestore(token) {
    if (!token) return;

    const devicesRef = this.afs.collection('devices');

    const docData = {
      token,
      userId: this.userUid,
    };

    return devicesRef.doc(token).set(docData)
  }
}

To use in your code is just include to page constructor:

public msgService: MessagingService

And use:

try {
    this.msgService.initializeFirebase(user.uid);
} catch (error) {
    console.log('fire push erro= ' + error);
}