我有一個帶有推送通知的 Ionic 5 Angular 應用程式,使用該@capacitor/push-notifications插件。按照此處所述正確設定,并在 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();
問題:推送通知“注冊”事件被觸發兩次,每次都有不同的令牌:
// 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)
}
}
}
兩個問題:
Gow 在不使用此處描述的另一個 FCM 插件的情況下防止那些重復的“注冊”事件?
如何以優雅的方式將 APN 與 FCM 令牌區分開來?
uj5u.com熱心網友回復:
你有兩NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications行,這就是將推送令牌發送到 JS 端的內容。
洗掉那個NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken),因為那是發送 APNS 令牌的那個。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/428870.html
上一篇:這是什么型別的計算機視覺任務?
