Ionic/Angular 上的电容器 - 事件 CapacitorDidRegisterForRemoteNotifications 未调用

问题描述 投票:0回答:1

我正在尝试实现一个具有推送通知功能的 Ionic Angular 应用程序(在 Android 和 iOS 上)。我为此使用官方电容器推送通知插件。

这是我在 AppDelegate.swift 文件中的内容:

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)
    }

}

我正在遵循本页上的教程:在 Ionic + Angular 应用程序中使用 Firebase 推送通知并且我正在我的 app.component.ts 文件上注册事件侦听器:

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');
            }
          }
        )
      }
    )
  }


}

但是,由于我需要在后端保存令牌以向特定用户发送通知,因此我在登录后请求权限,如果用户授予权限,我将调用注册函数:

  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();
              }
            )
          }
        )
      }
    )
  }

但是我创建了一个页面来显示收到的通知,在 iOS 上它不允许我显示它们,因为事件

capacitorDidRegisterForRemoteNotifications

从未被调用过。它在 Android 上完美运行。这是我的 notification.page.ts 文件:

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;
      }
    )
  }
  
}

这是我在 XCode 终端上遇到的错误:

[错误]-错误{“errorMessage”:“未调用事件capacitorjs.com/docs/apis/push-notifications了解更多信息”}

angular firebase ionic-framework capacitor capacitor-plugin
1个回答
0
投票
您需要启用iOS的功能设置。 参考:

链接 &此链接

© www.soinside.com 2019 - 2024. All rights reserved.