AppDelegate.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import UIKit
  17. import FirebaseCore
  18. import FirebaseMessaging
  19. import UserNotifications
  20. @UIApplicationMain
  21. class AppDelegate: UIResponder, UIApplicationDelegate {
  22. var window: UIWindow?
  23. static let isWithinUnitTest: Bool = {
  24. if let testClass = NSClassFromString("XCTestCase") {
  25. return true
  26. } else {
  27. return false
  28. }
  29. }()
  30. static var hasPresentedInvalidServiceInfoPlistAlert = false
  31. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  32. guard !AppDelegate.isWithinUnitTest else {
  33. // During unit tests, we don't want to initialize Firebase, since by default we want to able
  34. // to run unit tests without requiring a non-dummy GoogleService-Info.plist file
  35. return true
  36. }
  37. guard SampleAppUtilities.appContainsRealServiceInfoPlist() else {
  38. // We can't run because the GoogleService-Info.plist file is likely the dummy file which needs
  39. // to be replaced with a real one, or somehow the file has been removed from the app bundle.
  40. // See: https://github.com/firebase/firebase-ios-sdk/
  41. // We'll present a friendly alert when the app becomes active.
  42. return true
  43. }
  44. FirebaseApp.configure()
  45. Messaging.messaging().delegate = self
  46. Messaging.messaging().shouldEstablishDirectChannel = true
  47. // Just for logging to the console when we establish/tear down our socket connection.
  48. listenForDirectChannelStateChanges();
  49. NotificationsController.configure()
  50. if #available(iOS 8.0, *) {
  51. // Always register for remote notifications. This will not show a prompt to the user, as by
  52. // default it will provision silent notifications. We can use UNUserNotificationCenter to
  53. // request authorization for user-facing notifications.
  54. application.registerForRemoteNotifications()
  55. } else {
  56. // iOS 7 didn't differentiate between user-facing and other notifications, so we should just
  57. // register for remote notifications
  58. NotificationsController.shared.registerForUserFacingNotificationsFor(application)
  59. }
  60. return true
  61. }
  62. func application(_ application: UIApplication,
  63. didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  64. print("APNS Token: \(deviceToken.hexByteString)")
  65. NotificationCenter.default.post(name: APNSTokenReceivedNotification, object: nil)
  66. if #available(iOS 8.0, *) {
  67. } else {
  68. // On iOS 7, receiving a device token also means our user notifications were granted, so fire
  69. // the notification to update our user notifications UI
  70. NotificationCenter.default.post(name: UserNotificationsChangedNotification, object: nil)
  71. }
  72. }
  73. func application(_ application: UIApplication,
  74. didRegister notificationSettings: UIUserNotificationSettings) {
  75. NotificationCenter.default.post(name: UserNotificationsChangedNotification, object: nil)
  76. }
  77. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  78. print("application:didReceiveRemoteNotification:fetchCompletionHandler: called, with notification:")
  79. print("\(userInfo.jsonString ?? "{}")")
  80. completionHandler(.newData)
  81. }
  82. func applicationDidBecomeActive(_ application: UIApplication) {
  83. // If the app didn't start property due to an invalid GoogleService-Info.plist file, show an
  84. // alert to the developer.
  85. if !SampleAppUtilities.appContainsRealServiceInfoPlist() &&
  86. !AppDelegate.hasPresentedInvalidServiceInfoPlistAlert {
  87. if let vc = window?.rootViewController {
  88. SampleAppUtilities.presentAlertForInvalidServiceInfoPlistFrom(vc)
  89. AppDelegate.hasPresentedInvalidServiceInfoPlistAlert = true
  90. }
  91. }
  92. }
  93. }
  94. extension AppDelegate: MessagingDelegate {
  95. // FCM tokens are always provided here. It is called generally during app start, but may be called
  96. // more than once, if the token is invalidated or updated. This is the right spot to upload this
  97. // token to your application server, or to subscribe to any topics.
  98. func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
  99. if let token = Messaging.messaging().fcmToken {
  100. print("FCM Token: \(token)")
  101. } else {
  102. print("FCM Token: nil")
  103. }
  104. }
  105. // Direct channel data messages are delivered here, on iOS 10.0+.
  106. // The `shouldEstablishDirectChannel` property should be be set to |true| before data messages can
  107. // arrive.
  108. func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
  109. // Convert to pretty-print JSON
  110. guard let prettyPrinted = remoteMessage.appData.jsonString else {
  111. print("Received direct channel message, but could not parse as JSON: \(remoteMessage.appData)")
  112. return
  113. }
  114. print("Received direct channel message:\n\(prettyPrinted)")
  115. }
  116. }
  117. extension AppDelegate {
  118. func listenForDirectChannelStateChanges() {
  119. NotificationCenter.default.addObserver(self, selector: #selector(onMessagingDirectChannelStateChanged(_:)), name: .MessagingConnectionStateChanged, object: nil)
  120. }
  121. func onMessagingDirectChannelStateChanged(_ notification: Notification) {
  122. print("FCM Direct Channel Established: \(Messaging.messaging().isDirectChannelEstablished)")
  123. }
  124. }
  125. extension Dictionary {
  126. /// Utility method for printing Dictionaries as pretty-printed JSON.
  127. var jsonString: String? {
  128. if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted]),
  129. let jsonString = String(data: jsonData, encoding: .utf8) {
  130. return jsonString
  131. }
  132. return nil
  133. }
  134. }