AppDelegate.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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,
  32. didFinishLaunchingWithOptions launchOptions: [
  33. UIApplicationLaunchOptionsKey: Any
  34. ]?)
  35. -> Bool {
  36. guard !AppDelegate.isWithinUnitTest else {
  37. // During unit tests, we don't want to initialize Firebase, since by default we want to able
  38. // to run unit tests without requiring a non-dummy GoogleService-Info.plist file
  39. return true
  40. }
  41. guard SampleAppUtilities.appContainsRealServiceInfoPlist() else {
  42. // We can't run because the GoogleService-Info.plist file is likely the dummy file which needs
  43. // to be replaced with a real one, or somehow the file has been removed from the app bundle.
  44. // See: https://github.com/firebase/firebase-ios-sdk/
  45. // We'll present a friendly alert when the app becomes active.
  46. return true
  47. }
  48. FirebaseApp.configure()
  49. Messaging.messaging().delegate = self
  50. Messaging.messaging().shouldEstablishDirectChannel = true
  51. // Just for logging to the console when we establish/tear down our socket connection.
  52. listenForDirectChannelStateChanges()
  53. NotificationsController.configure()
  54. if #available(iOS 8.0, *) {
  55. // Always register for remote notifications. This will not show a prompt to the user, as by
  56. // default it will provision silent notifications. We can use UNUserNotificationCenter to
  57. // request authorization for user-facing notifications.
  58. application.registerForRemoteNotifications()
  59. } else {
  60. // iOS 7 didn't differentiate between user-facing and other notifications, so we should just
  61. // register for remote notifications
  62. NotificationsController.shared.registerForUserFacingNotificationsFor(application)
  63. }
  64. return true
  65. }
  66. func application(_ application: UIApplication,
  67. didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  68. print("APNS Token: \(deviceToken.hexByteString)")
  69. NotificationCenter.default.post(name: APNSTokenReceivedNotification, object: nil)
  70. if #available(iOS 8.0, *) {} else {
  71. // On iOS 7, receiving a device token also means our user notifications were granted, so fire
  72. // the notification to update our user notifications UI
  73. NotificationCenter.default.post(name: UserNotificationsChangedNotification, object: nil)
  74. }
  75. }
  76. func application(_ application: UIApplication,
  77. didRegister notificationSettings: UIUserNotificationSettings) {
  78. NotificationCenter.default.post(name: UserNotificationsChangedNotification, object: nil)
  79. }
  80. func application(_ application: UIApplication,
  81. didReceiveRemoteNotification userInfo: [AnyHashable: Any],
  82. fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult)
  83. -> Void) {
  84. print(
  85. "application:didReceiveRemoteNotification:fetchCompletionHandler: called, with notification:"
  86. )
  87. print("\(userInfo.jsonString ?? "{}")")
  88. completionHandler(.newData)
  89. }
  90. func applicationDidBecomeActive(_ application: UIApplication) {
  91. // If the app didn't start property due to an invalid GoogleService-Info.plist file, show an
  92. // alert to the developer.
  93. if !SampleAppUtilities.appContainsRealServiceInfoPlist(),
  94. !AppDelegate.hasPresentedInvalidServiceInfoPlistAlert {
  95. if let vc = window?.rootViewController {
  96. SampleAppUtilities.presentAlertForInvalidServiceInfoPlistFrom(vc)
  97. AppDelegate.hasPresentedInvalidServiceInfoPlistAlert = true
  98. }
  99. }
  100. }
  101. }
  102. extension AppDelegate: MessagingDelegate {
  103. // FCM tokens are always provided here. It is called generally during app start, but may be called
  104. // more than once, if the token is invalidated or updated. This is the right spot to upload this
  105. // token to your application server, or to subscribe to any topics.
  106. func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
  107. if let token = Messaging.messaging().fcmToken {
  108. print("FCM Token: \(token)")
  109. } else {
  110. print("FCM Token: nil")
  111. }
  112. }
  113. // Direct channel data messages are delivered here, on iOS 10.0+.
  114. // The `shouldEstablishDirectChannel` property should be be set to |true| before data messages can
  115. // arrive.
  116. func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
  117. // Convert to pretty-print JSON
  118. guard let prettyPrinted = remoteMessage.appData.jsonString else {
  119. print(
  120. "Received direct channel message, but could not parse as JSON: \(remoteMessage.appData)"
  121. )
  122. return
  123. }
  124. print("Received direct channel message:\n\(prettyPrinted)")
  125. }
  126. }
  127. extension AppDelegate {
  128. func listenForDirectChannelStateChanges() {
  129. NotificationCenter.default
  130. .addObserver(self, selector: #selector(onMessagingDirectChannelStateChanged(_:)),
  131. name: .MessagingConnectionStateChanged, object: nil)
  132. }
  133. func onMessagingDirectChannelStateChanged(_ notification: Notification) {
  134. print("FCM Direct Channel Established: \(Messaging.messaging().isDirectChannelEstablished)")
  135. }
  136. }
  137. extension Dictionary {
  138. /// Utility method for printing Dictionaries as pretty-printed JSON.
  139. var jsonString: String? {
  140. if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted]),
  141. let jsonString = String(data: jsonData, encoding: .utf8) {
  142. return jsonString
  143. }
  144. return nil
  145. }
  146. }