First time working on push notification. No previous knowledge on native development.
This is how my current files look like. Have tried sending test message from firebase but it is not working.
Am I missing something? I would truly appreciate advice on this matter.
Assumptions:
Firebase set up done and googleService.plist already added to the folder
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 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)
}
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)
}
}
ionic react implementation
import { IonHeader, IonPage, IonContent, IonToolbar, IonTitle, IonButton } from '@ionic/react';
import React, { useEffect, useState } from 'react';
import './TabCommon.css';
import { PushNotificationSchema, PushNotifications, Token, ActionPerformed } from '@capacitor/push-notifications';
import { Toast } from "@capacitor/toast";
const News: React.FC = () => {
const nullEntry: any[] = []
const [notifications, setnotifications] = useState(nullEntry);
useEffect(() => {
PushNotifications.addListener('registration', token => {
console.log('token ' + token.value);
});
PushNotifications.addListener('registrationError', (error: any) => {
console.log('error on register ' + JSON.stringify(error));
});
PushNotifications.addListener('pushNotificationReceived', notification => {
console.log('notification ' + JSON.stringify(notification));
notifications.push(notification);
});
PushNotifications.addListener('pushNotificationActionPerformed', notification => {
console.log('notification ' + JSON.stringify(notification));
notifications.push(notification);
console.log('Push notification action performed', notification.actionId, notification.inputValue);
});
}, [])
const showToast = async (msg: string) => {
await Toast.show({
text: msg
})
}
const register =()=>{
console.log("init")
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
// On success, we should be able to receive notifications
PushNotifications.addListener('registration',
(token: Token) => {
showToast('Push registration success');
});
// Show us the notification payload if the app is open on our device
PushNotifications.addListener('pushNotificationReceived',
(notification: PushNotificationSchema) => {
setnotifications(notifications => [...notifications, { id: notification.id, title: notification.title, body: notification.body, type: 'foreground' }])
}
);
console.log(notifications)
}
return (
<IonPage id='main'>
<IonHeader>
<IonToolbar color="primary">
<IonTitle slot="start"> Push Notifications</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding">
<IonButton color="success" expand="full" onClick={register}>Register for Push</IonButton>
</IonContent>
</IonPage >
)
};
export default News;
Thank you in advance