SampleStandaloneWatchAppApp.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2022 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import SwiftUI
  15. import FirebaseCore
  16. import FirebaseMessaging
  17. @main
  18. struct SampleStandaloneWatchApp_Watch_AppApp: App {
  19. @WKApplicationDelegateAdaptor(FCMWatchAppDelegate.self) var appDelegate
  20. var body: some Scene {
  21. WindowGroup {
  22. ContentView()
  23. }
  24. }
  25. }
  26. // MARK: - WKApplicationDelegate
  27. class FCMWatchAppDelegate: NSObject, WKApplicationDelegate, MessagingDelegate {
  28. func applicationDidFinishLaunching() {
  29. FirebaseApp.configure()
  30. let notificationCenter = UNUserNotificationCenter.current()
  31. notificationCenter.requestAuthorization(options: [.alert, .sound]) { granted, error in
  32. if granted {
  33. WKApplication.shared().registerForRemoteNotifications()
  34. }
  35. }
  36. Messaging.messaging().delegate = self
  37. }
  38. func didRegisterForRemoteNotifications(withDeviceToken deviceToken: Data) {
  39. // Method swizzling should be disabled in Firebase Messaging on watchOS.
  40. // Set the APNS token manually as is done here.
  41. // More information on how to disable -
  42. // https://firebase.google.com/docs/cloud-messaging/ios/client#method_swizzling_in
  43. print("APNS didRegisterForRemoteNotifications. Got device token \(deviceToken)")
  44. Messaging.messaging().apnsToken = deviceToken
  45. }
  46. }
  47. // MARK: - FCM MessagingDelegate
  48. extension FCMWatchAppDelegate {
  49. func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
  50. // Use this FCM token to test sending a push using API or Firebase Console
  51. print("FCM - didReceiveRegistrationToken \(String(describing: fcmToken))")
  52. }
  53. }