Ionic + Firebase - Push-уведомления - PullRequest
0 голосов
/ 12 декабря 2018

У меня есть приложение чата ionic + firebase, и я хотел бы отправить уведомление пользователю, когда получено новое сообщение.

В официальной документации Ionic рекомендуемый плагин для этого: https://github.com/katzer/cordova-plugin-local-notifications

Но, как вы можете видеть внутри репозитория, он не обновлялся с февраля прошлого года и, основываясь на комментариях внутри него, похоже, что он не работает с последними версиями ОС Android.

Кто-нибудь знает альтернативу?

Спасибо!

1 Ответ

0 голосов
/ 13 декабря 2018

У меня была та же проблема с внедрением push-уведомлений в моем приложении в прошлом месяце.Это лучший учебник для этого: https://medium.com/@senning/push-notifications-with-ionic-and-cordova-plugin-firebase-ab0c0cad3cc0

Я настроил этот учебник в файл: 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)
  }
}

Для использования в вашемкод просто включить на страницу конструктор :

public msgService: MessagingService

и использовать:

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