【问题标题】:Facing problem in integrating push notification in ionic 3 app for web platform在面向 Web 平台的 ionic 3 应用程序中集成推送通知时面临的问题
【发布时间】:2023-03-16 11:20:01
【问题描述】:

我正在使用 ionic 3 应用程序,其中 -:

解释 -: 1. 我正在开发 ionic 应用程序,我正在尝试使用 firebase 将 PUSH 通知集成到可能的应用程序中

我已经按照https://ionicframework.com/docs/native/push/的所有步骤进行操作

问题:推送通知不适用于 ios 和 android 的 Web 平台,但它正在工作。

**

请看:可能我没有正确放置 fcm,因为 ionic fcm 不是 支持网络,.

**

我把代码放在下面:

ts 文件-:

import { Push, PushOptions , PushObject } from '@ionic-native/push/ngx';


export class MyApp {
  rootPage:any = TabsPage;
  fcmId: any;

  constructor(   private storage: Storage , private alertCtrl: AlertController , private push: Push  , public navCtrl: NavController  , platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }



  initPushNotification() {
    // to check if we have permission
    this.push.hasPermission().then((res: any) => {
      if (res.isEnabled) {
        console.log('We have permission to send push notifications');
      } else {
        console.log("We don't have permission to send push notifications");
      }
    });

    // to initialize push notifications
    const options: PushOptions = {
      android: {
        senderID: '839584699716',
      },
      ios: {
        alert: 'true',
        badge: true,
        sound: 'false',
      },
      windows: {},
      browser: {
        pushServiceURL: 'http://push.api.phonegap.com/v1/push',
      },
     };

const pushObject: PushObject = this.push.init(options);

pushObject.on('notification').subscribe((notification: any) => {
console.log('Received a notification', notification);
//Notification Display Section
let confirmAlert = this.alertCtrl.create({
title: 'New Notification',
message: JSON.stringify(notification),
buttons: [
  {
    text: 'Ignore',
    role: 'cancel',
  },
  {
    text: 'View',
    handler: () => {
      //TODO: Your logic here
      //self.nav.push(DetailsPage, {message: data.message});
    },
  },
],
});
confirmAlert.present();
//
});
pushObject.on('registration').subscribe((registration: any) => {
console.log('Device registered', registration);
this.fcmId = registration.registrationId;
console.log(this.fcmId);
this.storage.set('fcmId', this.fcmId);
});

pushObject.on('error').subscribe(error => console.error('Error with Push plugin.....', error));
}

}

app.module.ts

import { AngularFireModule } from 'angularfire2';
import firebase from 'firebase';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireAuthModule } from 'angularfire2/auth'

import { Push } from '@ionic-native/push/ngx';
export const firebaseConfig = {
  apiKey: "AIzaSyBrU5I4_hK-M4Ai3#############",
  authDomain: "primeval-wind-230006.firebaseapp.com",
  databaseURL: "https://primeval-wind-230006.firebaseio.com",
  projectId: "primeval-wind-230006",
  storageBucket: "primeval-wind-230006.appspot.com",
  messagingSenderId: "##########"
}
firebase.initializeApp(firebaseConfig)

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage,
    SecondtryPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFireAuthModule,
    IonicStorageModule.forRoot()

  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage,
    SecondtryPage
  ],
  providers: [
    StatusBar,Push,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    GooglePlus
  ]
})
export class AppModule {}

【问题讨论】:

  • 如果你想在浏览器中使用 FCM,你不应该使用插件。我将尝试分享有关如何集成的步骤,但请注意使用的版本。

标签: ionic-framework ionic2 ionic3 angularfire2


【解决方案1】:

我将在这里分享适用于我的一个应用程序(Ionic 3、Angular 5.2.3)的方法:

在您的服务工作者中添加以下代码:

// FIREBASE:
importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase-messaging.js');

// firebase messaging part:
firebase.initializeApp({
    // get this from Firebase console, Cloud messaging section
    'messagingSenderId':'YOURIDHERE'
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler((payload) => {
    console.log('Received background message ', payload);
    // here you can override some options describing what's in the message;
    // however, the actual content will come from the Webtask
    const notificationOptions = {
        icon: '/assets/img/mstile-150x150.png'
    };
    return self.registration.showNotification(notificationTitle, notificationOptions);
});

然后在你的 app.module.ts 中导入火和消息模块:

import { AngularFireModule } from '@angular/fire';
import { AngularFireMessagingModule } from '@angular/fire/messaging';

确保您还将模块添加到 @NgModule 的导入部分:

AngularFireModule.initializeApp(ENV.FIREBASE_CONFIG),
AngularFireMessagingModule,

ENV 配置上方包含您的 fcm 配置:

FIREBASE_CONFIG: {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: ""
    },

现在是您的消息传递提供商:

import { AngularFireMessaging } from '@angular/fire/messaging';
...
constructor(
    private firebaseMessaging: AngularFireMessaging,
) {}
...

initFCMforPWA() {
    navigator.serviceWorker.getRegistration().then((registration)=>{
        this.firebaseMessaging.messaging.subscribe(
          (messaging) => {
            // we use this trick here to access useServiceWorker method:
            messaging.useServiceWorker(registration);

            // small workaround below (as I use ANGULAR FIRE 5.0.0):
            messaging.onTokenRefresh = messaging.onTokenRefresh.bind(messaging);
            // small work around above

            this.enableNotifications();
            // set flag that messaging was init:
            this.appHasFCMInitDone = true;
            messaging.onMessage((message)=>{
              console.log(message);
              this.toaster.presentSimpleToast(message.notification.title, "top");
            });
          },
          (error)=>{ console.log("failed to subscribe to firebase messaging")}
        );
      });
}

enableNotifications() {
    console.log("Requesting permission and token...");
    this.firebaseMessaging.requestToken.subscribe((token) => {
        console.log("Permission and token granted");
        this.fcmPermissionGranted = true;
        // send token to our server and set this for current user:
        this.setFCMToken(token).subscribe(
          () => { this.pushToken = token; console.log("token was set on server side") },
          (error) => {this.handleError(error)}
        )
      }, (error)=>{
        this.fcmPermissionGranted = false;
        console.log(error);
      });
  };

disableNotifications() {
    return new Promise((resolve, reject) =>{
      this.revokeFCMToken().subscribe(() => {
        this.pushToken = null;
        this.userID = null;
        this.userData = null;
        console.log("removed notification token from morphistic server");
          this.firebaseMessaging.getToken.pipe(mergeMap(token => this.firebaseMessaging.deleteToken(token))).subscribe(() => {
              console.log('deleted notification token from firebase');
              resolve();
            }
          );
        }
      );
    })
  };

请注意,您需要有自己的后端方法来设置和撤销令牌。

此配置适用于带有 AngularFire 5.0.0 的 Ionic 3/Angular 5.2.3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-29
    • 2015-04-12
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 2012-10-09
    相关资源
    最近更新 更多