ionic-team / capacitor

Build cross-platform Native Progressive Web Apps for iOS, Android, and the Web ⚑️
https://capacitorjs.com
MIT License
11.44k stars 977 forks source link

bug: Push Notifications listener `pushNotificationReceived` no longer firing with @capacitor/ios 2.0.0-beta.1 update #2646

Closed adonus19 closed 4 years ago

adonus19 commented 4 years ago

Bug Report

Capacitor Version

npx cap doctor output: @capacitor/cli 2.0.0-beta.1

@capacitor/core 2.0.0-beta.1

@capacitor/ios 2.0.0-beta.1

@capacitor/android 1.5.1

[success] Android looking great! πŸ‘Œ Found 3 Capacitor plugins for ios: capacitor-fcm (0.0.7) cordova-plugin-screen-orientation (3.0.2) es6-promise-plugin (4.2.2) [success] iOS looking great! πŸ‘Œ

Affected Platform(s)

Current Behavior

Previous version @capacitor/ios: 1.5.1 PushNotifications.addListener('pushNotificationReceived', (notification: PushNotification) would fire as expected. However, the latest version, @capacitor/ios 2.0.0-beta.1 listener is no longer firing. Same with listener pushNotificationActionPerformed.

Expected Behavior

A notification would be received while the app is in foreground/background.

Sample Code or Sample Application Repo

import { Component, OnInit } from '@angular/core';

import { Platform, ToastController, AlertController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { Plugins, PushNotification, PushNotificationToken, PushNotificationActionPerformed } from '@capacitor/core';
import { FCM } from 'capacitor-fcm';

const { PushNotifications } = Plugins;
const fcm = new FCM();

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})
export class AppComponent implements OnInit {
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private alert: AlertController
  ) {
    this.initializeApp();
  }

  ngOnInit() {
    console.log('Initializing the app');
    PushNotifications.register()
      .then(() => {
        return fcm.subscribeTo({ topic: 'relevant' });
      })
      .then(() => {});

    PushNotifications.addListener('registration', (token: PushNotificationToken) => {});

    PushNotifications.addListener('registrationError', (error: any) => {
      this.alert
        .create({
          header: 'Registration Error',
          message: 'There was a problem with registering for notifications',
          buttons: ['Ok'],
        })
        .then(alertEl => alertEl.present());
    });

    PushNotifications.addListener('pushNotificationReceived', (notification: PushNotification) => {
      this.alert
        .create({
          header: notification.title,
          message: notification.body,
          buttons: [
            {
              text: 'Ok',
              role: 'cancel',
              handler: () => PushNotifications.removeAllDeliveredNotifications(),
            },
          ],
        })
        .then(alertEl => alertEl.present());
    });

    PushNotifications.addListener('pushNotificationActionPerformed', (notification: 
      PushNotificationActionPerformed) => {
      this.alert
        .create({
          header: notification.notification.data.title,
          message: notification.notification.data.body,
          buttons: [
            {
              text: 'Ok',
              role: 'cancel',
              handler: () => PushNotifications.removeAllDeliveredNotifications(),
            },
          ],
        })
        .then(alertEl => alertEl.present());
    });
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }
}

Reproduction Steps

Follow the instructions to update your iOS platform in Capacitor docs here Specifically on these steps to update from @capacitor/ios: 1.5.1 to @capacitor/ios 2.0.0-beta.1:

npm install @capacitor/cli@next
npm install @capacitor/core@next
npm install @capacitor/ios@next
npx cap sync ios

Then run ionic capacitor run ios.

Other Technical Details

npm --version output: 6.13.7

node --version output: v11.14.0

pod --version output (iOS issues only): 1.9.1

Other Information

adonus19 commented 4 years ago

Closing as there is a new registration method specific to Capacitor v2. Adding this method will complete the notification registration process and allow push notifications to occur:

PushNotifications.requestPermission().then(result => {
      if (result.granted) {
        // Register with Apple / Google to receive push via APNS/FCM
        PushNotifications.register().then(() => {
          return fcm.subscribeTo({ topic: 'your-topic' });
        });
      } else {
        this.alert
          .create({
            header: 'Registration Error',
            message: 'There was a problem with registering for notifications',
            buttons: ['Ok'],
          })
          .then(alertEl => alertEl.present());
      }
    });
glaenzesch commented 4 years ago

Hi @adonus19: Is this working for you on iOS 13.x?

adonus19 commented 4 years ago

Yes, I have it working with iOS 13.4.

adonus19 commented 4 years ago

Sure! I got started with the tutorial in the Capacitor docs. You can find it here https://capacitor.ionicframework.com/docs/guides/push-notifications-firebase. I'm also using another package to add with subscribing to topics, "capacitor-fcm": "0.0.7",. For more info on subscribing to topics, you can look at Firebase's docs here https://firebase.google.com/docs/cloud-messaging/js/topic-messaging?authuser=0 .

Here is my code.

import { Component, OnInit } from '@angular/core'; import { Platform, ToastController, AlertController, ModalController } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { Plugins, PushNotification, PushNotificationToken, PushNotificationActionPerformed } from '@capacitor/core'; import { FCM } from 'capacitor-fcm'; const { PushNotifications } = Plugins; const fcm = new FCM(); @Component({ selector: 'app-root', templateUrl: 'app.component.html', styleUrls: ['app.component.scss'], }) export class AppComponent implements OnInit { constructor( private platform: Platform, private splashScreen: SplashScreen, private statusBar: StatusBar, private alert: AlertController, ) { this.initializeApp(); } ngOnInit() { console.log('Initializing the app'); PushNotifications.requestPermission().then(result => { if (result.granted) { // Register with Apple / Google to receive push via APNS/FCM PushNotifications.register().then(() => { return fcm.subscribeTo({ topic: 'your-topic' }); }); } else { this.alert .create({ header: 'Registration Error', message: 'There was a problem with registering for notifications', buttons: ['Ok'], }) .then(alertEl => alertEl.present()); } }); PushNotifications.addListener('registration', (token: PushNotificationToken) => {}); PushNotifications.addListener('registrationError', (error: any) => { this.alert .create({ header: 'Registration Error', message: 'There was a problem with registering for notifications', buttons: ['Ok'], }) .then(alertEl => alertEl.present()); }); } Also, here is snippet on how I am handling push notifications.

exports.yourCustomNotificationHandler = functions.https.onCall(data => { console.log('message received: ', data.message);

const note = { notification: { title: data.title, body: data.message, }, data: { body: data.message, title: data.title }, apns: { payload: { aps: { badge: 1, sound: 'default' }, }, }, android: { notification: { sound: 'default' }, }, topic: 'relevant', }; return admin .auth() .verifyIdToken(data.token) .then(result => { return admin.auth().getUser(result.uid); }) .then(user => { if (user.customClaims.admin) { return admin.messaging().send(note); } }) .then(data => { console.log(data); return { message: data }; }) .catch(err => { console.error('err in sending message: ', err); return { error: err }; }); });

Hope that helps!

Daniel Pogue

On Fri, Mar 27, 2020 at 8:47 AM Christopher Eurich notifications@github.com wrote:

Hi @adonus19 https://github.com/adonus19: Is this working for you on iOS 13.x?

β€” You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/ionic-team/capacitor/issues/2646#issuecomment-604981997, or unsubscribe https://github.com/notifications/unsubscribe-auth/AHGRYAAQPNGQTAJ7YR3HP63RJSN73ANCNFSM4LUYGHKA .

ionitron-bot[bot] commented 1 year ago

Thanks for the issue! This issue is being locked to prevent comments that are not relevant to the original issue. If this is still an issue with the latest version of Capacitor, please create a new issue and ensure the template is fully filled out.