skip to Main Content

I am trying to implement an Ionic Angular app with Push Notifications capabilities (both on Android and iOS). I am using the official Capacitor Push Notifications Plugin for this.

this is what i have on the AppDelegate.swift file:

import UIKit
import Capacitor
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()
        return true
        
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        // Called when the app was launched with a url. Feel free to add additional processing here,
        // but if you want the App API to support tracking app url opens, make sure to keep this call
        return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
    }

    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // Called when the app was launched with an activity, including Universal Links.
        // Feel free to add additional processing here, but if you want the App API to support
        // tracking app url opens, make sure to keep this call
        return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
      Messaging.messaging().apnsToken = deviceToken
      Messaging.messaging().token(completion: { (token, error) in
        if let error = error {
            NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
        } else if let token = token {
            NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: token)
        }
      })
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
      NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
    }

}

I am following the tutorial on this page: Using Push Notifications with Firebase in an Ionic + Angular App and I am registering the event listeners on my app.component.ts file:

export class AppComponent {

  _langs = ["es", "en"];

  constructor(
    private translate: TranslateService,
    private storage:StorageService,
    private toastCtrl:ToastController,
    private navCtrl:NavController,
    private sound:SoundService,
    private userService:UserService,
  ) {
    const _self = this;
    PushNotifications.addListener('registration',
    (token: Token) => {
      Device.getId().then(
        (id:DeviceId) => {
          _self.userService.registerFcm(token, id).then(
            (result:any) => {
              console.log(result.message);
            },
            (error) => {
              console.log(error.error);
            }
          )
        }
      )
    }
  );
  PushNotifications.addListener('registrationError',
    (error:any) => {
      console.log('PUSH NOTIFICATION ERROR', error.error);
    }
  );
    PushNotifications.addListener('pushNotificationReceived', notification => {
      if(notification.link) {
        _self.toastCtrl.create({
          header: notification.title,
          message: notification.body,
          color: 'sky',
          swipeGesture: 'vertical',
          position: 'top',
          duration: 5000,
          buttons: [
            {
              icon: 'open',
              side: 'end',
              handler: () => {
                _self.navCtrl.navigateForward(notification.link!);
              }
            }
          ]
        }).then(
          (toast) => {
            toast.present();
            _self.sound.play('assets/sounds/notification.mp3');
          }
        )
      } else {
        _self.toastCtrl.create({
          header: notification.title,
          message: notification.body,
          color: 'sky',
          swipeGesture: 'vertical',
          position: 'top',
          duration: 5000,
        }).then(
          (toast) => {
            toast.present();
            _self.sound.play('assets/sounds/notification.mp3');
          }
        )
      }
    });

    PushNotifications.addListener('pushNotificationActionPerformed', (notification) => {
      const data = notification.notification.data;
      if(data.url) {
        _self.navCtrl.navigateRoot(`${data.url}`);
      }
    });
    _self.initializeApp();
  }


  initializeApp() {
    Device.getLanguageCode().then(
      (deviceLanguage) => {
        this.storage.get('DEFAULT_LANGUAGE').then(
          (defaultLanguage) => {
            if(defaultLanguage && defaultLanguage.length > 0 && this._langs.find(supportedLanguage => supportedLanguage === defaultLanguage)) {
              this.translate.setDefaultLang(defaultLanguage);
            } else if(deviceLanguage && deviceLanguage.value.length > 0 && this._langs.find(supportedLanguage => supportedLanguage === deviceLanguage.value)) {
              this.translate.setDefaultLang(deviceLanguage.value);
            } else {
              this.translate.setDefaultLang('es');
            }
          }
        )
      }
    )
  }


}

but, since I need to save the token on the backend to send notifications to a specific user, I ask for permissions after login and if the user grants them i call the register function:

  submit() {
    const _self = this;
    _self.loadingCtrl.create({
      spinner: 'dots',
      message: _self.translate.instant('LOADERS.LOGGING_IN.MESSAGE'),
    }).then(
      (loader) => {
        loader.present();
        _self.authService.login(_self._loginForm.value).then(
          (success) => {
            _self.storage.set('AUTH_TOKEN', success.token).then(
              () => {
                _self.storage.set('USER_DATA', success.user_data).then(
                  async () => {
                    _self.navCtrl.navigateRoot('');
                    loader.dismiss();
                    _self.toastCtrl.create({
                      color: 'success',
                      message: _self.translate.instant('TOASTS.LOG_IN.SUCCESS'),
                      duration: 5000,
                      position: 'top',
                      swipeGesture: 'vertical'
                    }).then(
                      (toast) => {
                        toast.present();
                      }
                    )
                    await PushNotifications.addListener('registration',
                    (token: Token) => {
                      Device.getId().then(
                        (id:DeviceId) => {
                          _self.userService.registerFcm(token, id).then(
                            (result:any) => {
                              console.log(result.message);
                            },
                            (error) => {
                              console.log(error.error);
                            }
                          )
                        }
                      )
                    }
                  );
                  await PushNotifications.addListener('registrationError',
                    (error:any) => {
                      console.log('PUSH NOTIFICATION ERROR', error.error);
                    }
                  );
                    Device.getInfo().then(
                      (deviceInfo) => {
                        if(deviceInfo.platform !== "web") {
                          PushNotifications.checkPermissions().then(
                            (permissionStatus) => {
                              if(permissionStatus.receive == 'granted') {
                                PushNotifications.register();
                              }
                              else {
                                PushNotifications.requestPermissions().then(
                                  (requestResult) => {
                                    if(requestResult.receive == 'granted') {
                                      PushNotifications.register();
                                    }
                                  }
                                )
                              }
                            }
                          );
                        }
                      }
                    )
                    });
              }
            )
          },
          (error) => {
            _self.alertCtrl.create({
              header: _self.translate.instant('ALERTS.LOGIN_FAILED.HEADER'),
              subHeader: _self.translate.instant('ALERTS.LOGIN_FAILED.SUBHEADER'),
              message: (error.error.code == 401) ? _self.translate.instant('ALERTS.LOGIN_FAILED.INVALID_CREDENTIALS') :       _self.translate.instant('ALERTS.LOGIN_FAILED.GENERAL_ERROR'),
              buttons: [
                {
                  text: _self.translate.instant('BUTTONS.DISMISS'),
                  role: 'dismiss',
                }
              ]
            }).then(
              (alert) => {
                loader.dismiss();
                alert.present();
              }
            )
          }
        )
      }
    )
  }

but i created a page where I display the received notifications, on iOS it is not letting me display them because the event

capacitorDidRegisterForRemoteNotifications

is never called. It works perfectly on Android. this is my notifications.page.ts file:

export class NotificationsPage implements OnInit {

  _notifications: PushNotificationSchema[];

  constructor(
    private navCtrl:NavController,
  ) { }

  ngOnInit() {
    const _self = this;
    _self.getNotifications();
  }

  getNotifications() {
    PushNotifications.getDeliveredNotifications().then(
      (notifications:DeliveredNotifications) => {
        this._notifications = notifications.notifications;
      }
    )
  }
  
}

and this is the error that I get on XCode Terminal:

[error] – ERROR {"errorMessage":"event capacitorDidRegisterForRemoteNotifications not called. Visit https://capacitorjs.com/docs/apis/push-notifications for more information"}

2

Answers


  1. Chosen as BEST ANSWER

    As a follow up, I found a workaround and i added this to my home page to trigger the event listener on every login or when the app is killed, whenever it loads it goes to home page first.

      ngOnInit() {
        const _self = this;
        _self.registerNotifications();
      }
    
      ionViewWillEnter(): void {
        
      }
    
      registerNotifications() {
        const _self = this;
        PushNotifications.addListener('registration',
        (token: Token) => {
          console.log('Push registration success, token: ' + token.value);
          _self.storage.set('FCM_TOKEN', token).then(
            async () => {
              const deviceId = await Device.getId();
              _self.userService.registerFcm(token, deviceId).then(
                (success:any) => {
                  console.log('FCM Backend Result:', success.message);
                }
              )
            }
          )
        }
        );
        PushNotifications.addListener('registrationError',
        (error: any) => {
          console.log('Push registration error, message: ' + JSON.stringify(error));
        }
        );
        PushNotifications.checkPermissions().then(
          (permissions:PermissionStatus) => {
            if(permissions.receive == 'granted') {
              PushNotifications.register();
            } else {
              PushNotifications.requestPermissions().then(
                (result:PermissionStatus) => {
                  if(result.receive == 'granted') {
                    PushNotifications.register();
                  }
                }
              )
            }
          }
        )
      }

    the other listeners I kept in app.component.ts

    this seems to be working, with other issues but not regarding this specifically. Like I can't delete specific notifications using this function:

      getNotifications() {
        PushNotifications.getDeliveredNotifications().then(
          (notifications:DeliveredNotifications) => {
            this._notifications = notifications.notifications;
          }
        )
      }
    
    
      deleteNotification(notification: PushNotificationSchema) {
        let object:DeliveredNotifications = {
          notifications: [],
        };
        object.notifications.push(notification);
        PushNotifications.removeDeliveredNotifications(object);
        this.getNotifications();
      }


  2. You need to enable the capability settings for iOS.
    refer:link & this link

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search