离子电容器推送通知重复标记

Ionic capacitor push-notifications duplicate tokens

我有一个带推送通知的 Ionic 5 angular 应用程序,使用 @capacitor/push-notifications 插件。按照 here 和 iOS 上的 运行 所述正确设置。

推送通知服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Capacitor } from '@capacitor/core';
import {
    ActionPerformed,
    PushNotificationSchema,
    PushNotifications,
    Token,
} from '@capacitor/push-notifications';

import TXTS from '../../assets/strings.json';
import CFG from '../../app-config.json';

import { AppError } from './../error-handlers/app-errors';

@Injectable({ providedIn: 'root' })
export class PushNotificationService {
    private registerationToken: Token;

    constructor(
        private http: HttpClient
    ) {}

    /** initialize push plugin and add event listers to push notification events
     */
    init() {
        if (!this.isPushAvailable())
            return;

        // On success, we should be able to receive notifications
        PushNotifications.addListener('registration', (token: Token) => {
            console.log('Push registration success, token: ' + token.value);
            this.registerationToken = token;
            this.updateUserRegisterationToken();
        });

        PushNotifications.addListener('registrationError', (error: any) => {
            console.log('Error on registration: ' + JSON.stringify(error));
        });

        PushNotifications.addListener('pushNotificationReceived',
            (notification: PushNotificationSchema) => {
                // Show us the notification payload if the app is open on our device
                console.log('Push received: ' + JSON.stringify(notification));
            }
        );

        // Method called when tapping on a notification
        PushNotifications.addListener('pushNotificationActionPerformed',
            (notification: ActionPerformed) => {
                console.log('Push action performed: ' + JSON.stringify(notification));
            }
        );
    }

    /** Request permission to use push notifications
     */
    requestPermissions() {
        if (!this.isPushAvailable())
            return;

        PushNotifications.requestPermissions().then((result) => {
            if (result.receive === 'granted') {
                // Register with Apple / Google to receive push via APNS/FCM
                PushNotifications.register();
            } else {
                throw new AppError(TXTS.userWarnings.noPushPermissions);
            }
        });
    }

    private isPushAvailable() {
        return Capacitor.isPluginAvailable('PushNotifications');
    }

    private updateUserRegisterationToken() {
        this.http
            .post(
                CFG.apiEndpoints.userPushRegistrationToken,
                { token: this.registerationToken.value }
            )
            .subscribe(
                () => this.handleSuccessfulRegistrationTokenUpdate(),
                (error) => this.handleFailedRegistrationTokenUpdate(error)
            );
    }

    private handleSuccessfulRegistrationTokenUpdate() {
        console.log('Registration token was updated on server');
    }

    private handleFailedRegistrationTokenUpdate(error) {
        throw new Error('Error updating push registration token on server. Error: ' + error); // Not AppError! Not to show error to the user.
    }
}

推送服务由应用通过调用初始化:

this.pushService.requestPermissions();
this.pushService.init();

问题: 推送通知 'registration' 事件被触发两次,每次都有不同的标记:

// from xCode logs:
Push registration success, token: 2014C60FE7FB063F2ED833E7B4DF3D0220EE31EEF3350E56C3C0CE3006BD62BE

Push registration success, token: dx7g0rZPZUBCkxFFpgPaQr:APA91bF6xCk9oZje7NNrAu1-_OB1y2Kek9RxOQMGVrxahqgCDh8YZv5W_aekKgJJtFAQqA0e__K-qqtB5c9T28PFc542R7MuYQYuKkztOet3gWpPU-zF3lUsLLeXwU45On7KDpEuG5I1

我知道第一个令牌是 APN 令牌,第二个是 firebase (FCM) 令牌。我的项目只需要 firebase 令牌,而 APN 令牌导致混淆。

我的 AppDeligate.swift 看起来像他的:

import UIKit
import Firebase
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 application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)

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

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

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)

        let statusBarRect = UIApplication.shared.statusBarFrame
        guard let touchPoint = event?.allTouches?.first?.location(in: self.window) else { return }

        if statusBarRect.contains(touchPoint) {
            NotificationCenter.default.post(name: .capacitorStatusBarTapped, object: nil)
        }
    }

}

两个问题:

  1. Gow 在不使用另一个的情况下防止那些重复的 'registration' 事件 描述的 FCM 插件 here?

  2. 如何以优雅的方式区分 APN 和 FCM 令牌?

你有两行 NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications 行,这就是将推送令牌发送到 JS 端的内容。

删除 NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken) 那个发送 APNS 令牌的那个。