I have one swiftUI iPhone application. I have added watch application target for iPhone application. I have registered for push notification in iPhone application using following code.
class AppDelegate: NSObject, UIApplicationDelegate, MessagingDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
FirebaseApp.configure()
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .sound, .badge]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { _, error in
if error != nil {
// we are ready to go
}
}
application.registerForRemoteNotifications()
return true
}
}
I want to receive push notification in apple watch and on click of that push notification, it should display specific screen in watch OS Application. How to register push notification in watch OS?
Will this code WKExtension.shared().registerForRemoteNotifications()
be used for registering push notification in watch os? Where to add this code as SwiftUI watch app contains no watch extension.
Used following code to register for push notification in watch os
import SwiftUI
import FirebaseCore
import FirebaseMessaging
@main
struct SampleStandaloneWatchApp_Watch_AppApp: App {
@WKApplicationDelegateAdaptor(FCMWatchAppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
// MARK: - WKApplicationDelegate
class FCMWatchAppDelegate: NSObject, WKApplicationDelegate, MessagingDelegate {
func applicationDidFinishLaunching() {
FirebaseApp.configure()
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.requestAuthorization(options: [.alert, .sound]) { granted, error in
if granted {
WKApplication.shared().registerForRemoteNotifications()
}
}
Messaging.messaging().delegate = self
}
func didRegisterForRemoteNotifications(withDeviceToken deviceToken: Data) {
// Method swizzling should be disabled in Firebase Messaging on watchOS.
// Set the APNS token manually as is done here.
// More information on how to disable -
// https://firebase.google.com/docs/cloud-messaging/ios/client#method_swizzling_in
print("APNS didRegisterForRemoteNotifications. Got device token \(deviceToken)")
Messaging.messaging().apnsToken = deviceToken
}
}
// MARK: - FCM MessagingDelegate
extension FCMWatchAppDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
// Use this FCM token to test sending a push using API or Firebase Console
print("FCM - didReceiveRegistrationToken \(String(describing: fcmToken))")
}
}