ExtensionDelegate.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. import FirebaseRemoteConfig
  18. /// Entry point of the watch app.
  19. class ExtensionDelegate: NSObject, WKExtensionDelegate, MessagingDelegate {
  20. /// Initialize Firebase service here.
  21. func applicationDidFinishLaunching() {
  22. FirebaseApp.configure()
  23. let center = UNUserNotificationCenter.current()
  24. center.requestAuthorization(options: [.alert, .sound]) { granted, _ in
  25. if granted {
  26. WKExtension.shared().registerForRemoteNotifications()
  27. }
  28. }
  29. Messaging.messaging().delegate = self
  30. let remoteConfig = RemoteConfig.remoteConfig()
  31. remoteConfig.fetchAndActivate { _, error in
  32. guard error == nil else {
  33. print("error:" + error.debugDescription)
  34. return
  35. }
  36. let defaultOutput = "You have not set up a 'test' key in Remote Config console."
  37. let configValue: String =
  38. remoteConfig["test"].stringValue ?? defaultOutput
  39. print("value:\n" + configValue)
  40. }
  41. }
  42. /// MessagingDelegate
  43. func messaging(_: Messaging, didReceiveRegistrationToken fcmToken: String?) {
  44. print("token:\n" + fcmToken!)
  45. Messaging.messaging().subscribe(toTopic: "watch") { error in
  46. guard error == nil else {
  47. print("error:" + error.debugDescription)
  48. return
  49. }
  50. print("Successfully subscribed to topic")
  51. }
  52. }
  53. /// WKExtensionDelegate
  54. func didRegisterForRemoteNotifications(withDeviceToken deviceToken: Data) {
  55. /// Swizzling should be disabled in Messaging for watchOS, set APNS token manually.
  56. print("Set APNS Token\n")
  57. Messaging.messaging().apnsToken = deviceToken
  58. }
  59. }