Issue
I have an Ionic 5 angular app with push notifications, using the @capacitor/push-notifications
plugin. Set up correctly as described here, and running on iOS.
PushNotificationService:
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.
}
}
The push service is initialized by the app by calling:
this.pushService.requestPermissions();
this.pushService.init();
The problem: Push Notifications 'registration' event is fired twice, each with a different token:
// from xCode logs:
Push registration success, token: 2014C60FE7FB063F2ED833E7B4DF3D0220EE31EEF3350E56C3C0CE3006BD62BE
Push registration success, token: dx7g0rZPZUBCkxFFpgPaQr:APA91bF6xCk9oZje7NNrAu1-_OB1y2Kek9RxOQMGVrxahqgCDh8YZv5W_aekKgJJtFAQqA0e__K-qqtB5c9T28PFc542R7MuYQYuKkztOet3gWpPU-zF3lUsLLeXwU45On7KDpEuG5I1
I understand that the first token is an APN token, and the second is a firebase (FCM) token. My project needs only the firebase token, and the APN token causes confusion.
My AppDeligate.swift looks like his:
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)
}
}
}
Two questions:
Gow to prevent those duplicate 'registration' events without using another FCM plugin as described here?
How to diffrentiate APN from the FCM token in an elgant way?
Solution
You have two NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications
lines, that's what sends the push token to the JS side.
Remove the NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
one as that's the one sending the APNS token.
Answered By - jcesarmobile
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.