AppDelegate.swift 6.3 KB

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