ExtensionDelegate.swift 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2020 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 WatchKit
  15. import FirebaseCore
  16. import FirebaseMessaging
  17. /// Entry point of the watch app.
  18. class ExtensionDelegate: NSObject, WKExtensionDelegate, MessagingDelegate {
  19. /// Initialize Firebase service here.
  20. func applicationDidFinishLaunching() {
  21. FirebaseApp.configure()
  22. let center = UNUserNotificationCenter.current()
  23. center.requestAuthorization(options: [.alert, .sound]) { granted, error in
  24. if granted {
  25. WKExtension.shared().registerForRemoteNotifications()
  26. }
  27. }
  28. Messaging.messaging().delegate = self
  29. }
  30. /// MessagingDelegate
  31. func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
  32. print("token:\n" + fcmToken)
  33. Messaging.messaging().subscribe(toTopic: "watch") { error in
  34. if error != nil {
  35. print("error:" + error.debugDescription)
  36. } else {
  37. print("Successfully subscribed to topic")
  38. }
  39. }
  40. }
  41. /// WKExtensionDelegate
  42. func didRegisterForRemoteNotifications(withDeviceToken deviceToken: Data) {
  43. /// Swizzling should be disabled in Messaging for watchOS, set APNS token manually.
  44. print("Set APNS Token\n")
  45. Messaging.messaging().apnsToken = deviceToken
  46. }
  47. }