ExtensionDelegate.swift 1.7 KB

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