首页 > 解决方案 > Ionic 4 FCM onNotification 未被调用

问题描述

我正在使用cordova-plugin-fcm-with-dependecy-updated来接收推送通知,但是this.fcm.onNotificationobservable 没有被执行。我可以在 Xcode 控制台中看到正在接收消息,并且单步执行我可以看到的代码-(void) notifyOfMessage:(NSData *)payload是从内部调用的,FCMPlugin.m但我无法确定为什么this.fcm.onNotification没有被调用。

我可以在控制台中看到FCMPlugin.js: is createdFCMPlugin Ready OK,在下面几行我可以看到我添加的 console.log 以确认this.platform.ready正在调用(这是我fcm.onNotification从内部订阅的地方app.component.ts

值得注意的是,当应用程序关闭或暂停时我会收到通知,只是当应用程序处于前台时我无法捕获收到通知以提醒用户的时间,以及点击通知时我不能读取wasTapped属性将用户重定向到特定页面(因为onNotification没有被触发)。

有人对问题的原因有任何想法吗?

我在用着:

@Ionic/angular: ^4.11.4
cordova-android: ^8.1.0
cordova-ios: ^5.0.1
cordova-plugin-fcm-with-dependecy-updated: ^4.1.0
FCM_CORE_VERSION: 16.0.9
FCM_VERSION: 18.0.0,
GRADLE_TOOLS_VERSION: 3.5.0,
GOOGLE_SERVICES_VERSION: 4.2.0

标签: cordovaionic-frameworkfirebase-cloud-messaging

解决方案


我已经找到了可以满足我当前需求的可怕解决方法,但并不能完全解决手头的问题。

对于 iOS,而不是将以下代码放入app.component.ts constructor

this.platform.ready().then(() => {
  this.fcm.onNotification().subscribe(data => { 
    // Do stuff here
  });
});

我将以下代码放入this.initializeApp()

async this.initializeApp() {

  try { 

    let isReady = await this.platform.ready();

    if (isReady) {

      if (this.platform.is('ios') === true) {

        this.fcm.onNotification().subscribe(data => { 
          // Do stuff
        });

      }

    }

  } catch (err) {

    // Deal with error

  }

  // Do other app init stuff

}

对我来说为什么await会工作而不是没有任何意义this.platform.ready().then(),但无论出于何种原因,上述适用于 iOS。

要开始onNotification为 Android 工作,我需要将以下内容放入app.component.ts constructor

if (this.platform.is('android') === true) {

  this.platform.ready().then(() => {

    setTimeout(() => {

      this.fcm.onNotification().subscribe(data => { 
        // Do stuff here
      });

    }, 100);

  });

}

同样,我不知道为什么会这样。但是在这个问题上花了几天时间之后,这是我想出的一个可以接受的解决方案。

不过,上面的 Android 代码存在问题。只有当应用程序在前台时,onNotificationobservable 才会触发。当它关闭或暂停时,您会收到通知并点击它,onNotificationobservable 不会被触发。:(


推荐阅读