AppDelegate.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import UIKit
  2. import SafariServices
  3. import UserNotifications
  4. import Firebase
  5. import FirebaseCore
  6. import CoreData
  7. // https://stackoverflow.com/a/41783666/1440785
  8. // https://stackoverflow.com/questions/47374903/viewing-core-data-data-from-your-app-on-a-device
  9. class AppDelegate: UIResponder, UIApplicationDelegate {
  10. let tag = "AppDelegate"
  11. let store = Store.shared
  12. func application(
  13. _ application: UIApplication,
  14. didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  15. ) -> Bool {
  16. Log.d(tag, "ApplicationDelegate didFinishLaunchingWithOptions.")
  17. // FirebaseApp.configure() DOES NOT WORK
  18. FirebaseConfiguration.shared.setLoggerLevel(.max)
  19. Messaging.messaging().delegate = self
  20. registerForPushNotifications()
  21. UNUserNotificationCenter.current().delegate = self
  22. return true
  23. }
  24. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  25. guard let aps = userInfo["aps"] as? [String: AnyObject] else {
  26. completionHandler(.failed)
  27. return
  28. }
  29. print("didReceiveRemoteNotification")
  30. print(userInfo)
  31. }
  32. func application(_ application: UIApplication,
  33. didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  34. print("didReceiveRemoteNotification 2")
  35. guard let aps = userInfo["aps"] as? [String: AnyObject] else {
  36. return
  37. }
  38. print(userInfo)
  39. }
  40. func application(
  41. _ application: UIApplication,
  42. didFailToRegisterForRemoteNotificationsWithError error: Error
  43. ) {
  44. print("Failed to register: \(error)")
  45. }
  46. // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
  47. // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
  48. // the FCM registration token.
  49. func application(_ application: UIApplication,
  50. didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  51. print("APNs token retrieved: \(deviceToken)")
  52. // With swizzling disabled you must set the APNs token here.
  53. Messaging.messaging().apnsToken = deviceToken
  54. let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
  55. let token = tokenParts.joined()
  56. print("Device Token: \(token)")
  57. }
  58. func registerForPushNotifications() {
  59. UNUserNotificationCenter.current()
  60. .requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in
  61. print("granted: \(granted)")
  62. guard granted else { return }
  63. self?.getNotificationSettings()
  64. }
  65. }
  66. func getNotificationSettings() {
  67. UNUserNotificationCenter.current().getNotificationSettings { settings in
  68. print("Notification settings: \(settings)")
  69. guard settings.authorizationStatus == .authorized else { return }
  70. DispatchQueue.main.async {
  71. UIApplication.shared.registerForRemoteNotifications()
  72. }
  73. }
  74. }
  75. }
  76. extension AppDelegate: UNUserNotificationCenterDelegate {
  77. func userNotificationCenter(
  78. _ center: UNUserNotificationCenter,
  79. willPresent notification: UNNotification,
  80. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
  81. ) {
  82. let userInfo = notification.request.content.userInfo
  83. Log.d(tag, "Notification received via userNotificationCenter(willPresent)", userInfo)
  84. store.saveNotification(fromUserInfo: userInfo)
  85. completionHandler([[.alert, .sound]])
  86. }
  87. func userNotificationCenter(
  88. _ center: UNUserNotificationCenter,
  89. didReceive response: UNNotificationResponse,
  90. withCompletionHandler completionHandler: @escaping () -> Void
  91. ) {
  92. let userInfo = response.notification.request.content.userInfo
  93. Log.d(tag, "Notification received via userNotificationCenter(didReceive)", userInfo)
  94. store.saveNotification(fromUserInfo: userInfo)
  95. completionHandler()
  96. }
  97. }
  98. extension AppDelegate: MessagingDelegate {
  99. func messaging(
  100. _ messaging: Messaging,
  101. didReceiveRegistrationToken fcmToken: String?
  102. ) {
  103. Log.d(tag, "Firebase token received: \(String(describing: fcmToken))")
  104. // FIXME: Is this necessary?
  105. let dataDict: [String: String] = ["token": fcmToken ?? ""]
  106. NotificationCenter.default.post(
  107. name: UserNotifications.Notification.Name("FCMToken"),
  108. object: nil,
  109. userInfo: dataDict
  110. )
  111. }
  112. }