AppDelegate.swift 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. //
  2. // AppDelegate.swift
  3. // Sirani
  4. //
  5. // Created by Anhar Solehudin on 24/03/19.
  6. // Copyright © 2019 Anhar Solehudin. All rights reserved.
  7. //
  8. import UIKit
  9. import GoogleMaps
  10. import UserNotifications
  11. import Firebase
  12. import SDWebImageWebPCoder
  13. @UIApplicationMain
  14. class AppDelegate: UIResponder, UIApplicationDelegate {
  15. var window: UIWindow?
  16. /// set orientations you want to be allowed in this property by default
  17. var orientationLock = UIInterfaceOrientationMask.all
  18. func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
  19. return self.orientationLock
  20. }
  21. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  22. // Override point for customization after application launch.
  23. // Aktifkan WebP Coder
  24. SDImageCodersManager.shared.addCoder(SDImageWebPCoder.shared)
  25. GMSServices.provideAPIKey("AIzaSyC8OxBL_ADTFubfkmZ2I81-IXx4O7t6Tog")
  26. // AIzaSyDOdr-zkd6oLhHRE-prsu23-u7rnSh5WCY // id.go.postel.sirani
  27. // Init Firebase Messaging
  28. FirebaseApp.configure()
  29. Messaging.messaging().delegate = self
  30. if #available(iOS 10.0, *) {
  31. // For iOS 10 display notification (sent via APNS)
  32. UNUserNotificationCenter.current().delegate = self
  33. let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
  34. UNUserNotificationCenter.current().requestAuthorization(
  35. options: authOptions,
  36. completionHandler: {_, _ in })
  37. } else {
  38. let settings: UIUserNotificationSettings =
  39. UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
  40. application.registerUserNotificationSettings(settings)
  41. }
  42. application.registerForRemoteNotifications()
  43. Messaging.messaging().token { token, error in
  44. if let error = error {
  45. print("Error fetching FCM registration token: \(error)")
  46. } else if let token = token {
  47. print("FCM registration token: \(token)")
  48. self.postFcmToken(fcmToken: token)
  49. }
  50. }
  51. return true
  52. }
  53. func applicationWillResignActive(_ application: UIApplication) {
  54. // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
  55. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  56. }
  57. func applicationDidEnterBackground(_ application: UIApplication) {
  58. // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
  59. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  60. }
  61. func applicationWillEnterForeground(_ application: UIApplication) {
  62. // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
  63. }
  64. func applicationDidBecomeActive(_ application: UIApplication) {
  65. // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  66. }
  67. func applicationWillTerminate(_ application: UIApplication) {
  68. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  69. }
  70. // [START receive_message]
  71. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  72. // If you are receiving a notification message while your app is in the background,
  73. // this callback will not be fired till the user taps on the notification launching the application.
  74. // TODO: Handle data of notification
  75. // With swizzling disabled you must let Messaging know about the message, for Analytics
  76. // Messaging.messaging().appDidReceiveMessage(userInfo)
  77. // Print message ID.
  78. // if let messageID = userInfo[gcmMessageIDKey] {
  79. // print("Message ID: \(messageID)")
  80. // }
  81. // Print full message.
  82. print(userInfo)
  83. }
  84. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
  85. fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  86. // If you are receiving a notification message while your app is in the background,
  87. // this callback will not be fired till the user taps on the notification launching the application.
  88. // TODO: Handle data of notification
  89. // With swizzling disabled you must let Messaging know about the message, for Analytics
  90. // Messaging.messaging().appDidReceiveMessage(userInfo)
  91. // Print message ID.
  92. // if let messageID = userInfo[gcmMessageIDKey] {
  93. // print("Message ID: \(messageID)")
  94. // }
  95. // Print full message.
  96. print(userInfo)
  97. completionHandler(UIBackgroundFetchResult.newData)
  98. }
  99. // [END receive_message]
  100. func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  101. print("Unable to register for remote notifications: \(error.localizedDescription)")
  102. }
  103. // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
  104. // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
  105. // the FCM registration token.
  106. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  107. print("APNs token retrieved: \(deviceToken)")
  108. // With swizzling disabled you must set the APNs token here.
  109. // Messaging.messaging().apnsToken = deviceToken
  110. }
  111. }
  112. // [START ios_10_message_handling]
  113. @available(iOS 10, *)
  114. extension AppDelegate : UNUserNotificationCenterDelegate {
  115. // Receive displayed notifications for iOS 10 devices.
  116. func userNotificationCenter(_ center: UNUserNotificationCenter,
  117. willPresent notification: UNNotification,
  118. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  119. let userInfo = notification.request.content.userInfo
  120. // With swizzling disabled you must let Messaging know about the message, for Analytics
  121. // Messaging.messaging().appDidReceiveMessage(userInfo)
  122. // Print message ID.
  123. // if let messageID = userInfo[gcmMessageIDKey] {
  124. // print("Message ID: \(messageID)")
  125. // }
  126. // Print full message.
  127. print(userInfo)
  128. // Change this to your preferred presentation option
  129. completionHandler([[.alert, .sound]])
  130. }
  131. func userNotificationCenter(_ center: UNUserNotificationCenter,
  132. didReceive response: UNNotificationResponse,
  133. withCompletionHandler completionHandler: @escaping () -> Void) {
  134. let userInfo = response.notification.request.content.userInfo
  135. // Print message ID.
  136. // if let messageID = userInfo[gcmMessageIDKey] {
  137. // print("Message ID: \(messageID)")
  138. // }
  139. // With swizzling disabled you must let Messaging know about the message, for Analytics
  140. // Messaging.messaging().appDidReceiveMessage(userInfo)
  141. // Print full message.
  142. print(userInfo)
  143. // notif handler : open noti list page
  144. if let tabBarController = self.window?.rootViewController as? UITabBarController {
  145. tabBarController.selectedViewController?.performSegue(withIdentifier: "NotifListSegueId", sender: tabBarController.selectedViewController.self)
  146. }
  147. // tell the app that we have finished processing the user’s action / response
  148. completionHandler()
  149. }
  150. }
  151. // [END ios_10_message_handling]
  152. extension AppDelegate : MessagingDelegate {
  153. // [START refresh_token]
  154. func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
  155. print("Firebase registration token: \(String(describing: fcmToken))")
  156. if let token = fcmToken {
  157. self.postFcmToken(fcmToken: token)
  158. }
  159. let dataDict:[String: String] = ["token": fcmToken ?? ""]
  160. NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
  161. // TODO: If necessary send token to application server.
  162. // Note: This callback is fired at each app startup and whenever a new token is generated.
  163. }
  164. // [END refresh_token]
  165. }
  166. extension AppDelegate {
  167. private func postFcmToken(fcmToken: String) {
  168. let isLogin = UserState.instance.isLoggedIn()
  169. if isLogin {
  170. let userId = UserState.instance.getUserId()
  171. let roleId = UserState.instance.getRoleId()
  172. SiraniApiServices().postFcmToken(user_id: userId, role_id: roleId, fcmToken: fcmToken).responseJSON { response in
  173. if response.error == nil {
  174. print("FCM User Token Updated To Server : \(fcmToken)")
  175. }
  176. }
  177. }
  178. }
  179. }