AppDelegate.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. let primaryBlue = UIColor.siraniPrimaryBlue
  24. // Setup Global Navigation Bar Appearance
  25. if #available(iOS 15.0, *) {
  26. let navAppearance = UINavigationBarAppearance()
  27. navAppearance.configureWithOpaqueBackground()
  28. navAppearance.backgroundColor = primaryBlue
  29. navAppearance.titleTextAttributes = [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 18, weight: .bold)]
  30. navAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 28, weight: .bold)]
  31. UINavigationBar.appearance().standardAppearance = navAppearance
  32. UINavigationBar.appearance().scrollEdgeAppearance = navAppearance
  33. UINavigationBar.appearance().compactAppearance = navAppearance
  34. } else {
  35. UINavigationBar.appearance().barTintColor = primaryBlue
  36. UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.white]
  37. UINavigationBar.appearance().isTranslucent = false
  38. }
  39. // Setup Back Button & Icons color to White globally
  40. UINavigationBar.appearance().tintColor = .white
  41. // Setup Global Tab Bar Appearance (Clean White background with Sirani Blue active state)
  42. if #available(iOS 15.0, *) {
  43. let appearance = UITabBarAppearance()
  44. appearance.configureWithOpaqueBackground()
  45. appearance.backgroundColor = .white
  46. appearance.shadowColor = UIColor.black.withAlphaComponent(0.08)
  47. // Set warna unselected (abu-abu netral)
  48. let unselectedColor = UIColor.siraniUnselectedGray
  49. appearance.stackedLayoutAppearance.normal.iconColor = unselectedColor
  50. appearance.stackedLayoutAppearance.normal.titleTextAttributes = [
  51. .foregroundColor: unselectedColor,
  52. .font: UIFont.systemFont(ofSize: 10, weight: .medium)
  53. ]
  54. // Set warna selected (Biru Utama SIRANI)
  55. appearance.stackedLayoutAppearance.selected.iconColor = primaryBlue
  56. appearance.stackedLayoutAppearance.selected.titleTextAttributes = [
  57. .foregroundColor: primaryBlue,
  58. .font: UIFont.systemFont(ofSize: 10, weight: .bold)
  59. ]
  60. UITabBar.appearance().standardAppearance = appearance
  61. UITabBar.appearance().scrollEdgeAppearance = appearance
  62. } else {
  63. UITabBar.appearance().backgroundColor = .white
  64. UITabBar.appearance().unselectedItemTintColor = UIColor.siraniUnselectedGray
  65. UITabBar.appearance().tintColor = primaryBlue
  66. }
  67. // Aktifkan WebP Coder
  68. SDImageCodersManager.shared.addCoder(SDImageWebPCoder.shared)
  69. GMSServices.provideAPIKey("AIzaSyC8OxBL_ADTFubfkmZ2I81-IXx4O7t6Tog")
  70. // AIzaSyDOdr-zkd6oLhHRE-prsu23-u7rnSh5WCY // id.go.postel.sirani
  71. // Init Firebase Messaging
  72. FirebaseApp.configure()
  73. Messaging.messaging().delegate = self
  74. if #available(iOS 10.0, *) {
  75. // For iOS 10 display notification (sent via APNS)
  76. UNUserNotificationCenter.current().delegate = self
  77. let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
  78. UNUserNotificationCenter.current().requestAuthorization(
  79. options: authOptions,
  80. completionHandler: {_, _ in })
  81. } else {
  82. let settings: UIUserNotificationSettings =
  83. UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
  84. application.registerUserNotificationSettings(settings)
  85. }
  86. application.registerForRemoteNotifications()
  87. Messaging.messaging().token { token, error in
  88. if let error = error {
  89. print("Error fetching FCM registration token: \(error)")
  90. } else if let token = token {
  91. print("FCM registration token: \(token)")
  92. self.postFcmToken(fcmToken: token)
  93. }
  94. }
  95. return true
  96. }
  97. func applicationWillResignActive(_ application: UIApplication) {
  98. // 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.
  99. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  100. }
  101. func applicationDidEnterBackground(_ application: UIApplication) {
  102. // 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.
  103. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  104. }
  105. func applicationWillEnterForeground(_ application: UIApplication) {
  106. // 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.
  107. }
  108. func applicationDidBecomeActive(_ application: UIApplication) {
  109. // 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.
  110. }
  111. func applicationWillTerminate(_ application: UIApplication) {
  112. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  113. }
  114. // [START receive_message]
  115. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  116. // If you are receiving a notification message while your app is in the background,
  117. // this callback will not be fired till the user taps on the notification launching the application.
  118. // TODO: Handle data of notification
  119. // With swizzling disabled you must let Messaging know about the message, for Analytics
  120. // Messaging.messaging().appDidReceiveMessage(userInfo)
  121. // Print message ID.
  122. // if let messageID = userInfo[gcmMessageIDKey] {
  123. // print("Message ID: \(messageID)")
  124. // }
  125. // Print full message.
  126. print(userInfo)
  127. }
  128. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
  129. fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  130. // If you are receiving a notification message while your app is in the background,
  131. // this callback will not be fired till the user taps on the notification launching the application.
  132. // TODO: Handle data of notification
  133. // With swizzling disabled you must let Messaging know about the message, for Analytics
  134. // Messaging.messaging().appDidReceiveMessage(userInfo)
  135. // Print message ID.
  136. // if let messageID = userInfo[gcmMessageIDKey] {
  137. // print("Message ID: \(messageID)")
  138. // }
  139. // Print full message.
  140. print(userInfo)
  141. completionHandler(UIBackgroundFetchResult.newData)
  142. }
  143. // [END receive_message]
  144. func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  145. print("Unable to register for remote notifications: \(error.localizedDescription)")
  146. }
  147. // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
  148. // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
  149. // the FCM registration token.
  150. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  151. print("APNs token retrieved: \(deviceToken)")
  152. // With swizzling disabled you must set the APNs token here.
  153. // Messaging.messaging().apnsToken = deviceToken
  154. }
  155. }
  156. // [START ios_10_message_handling]
  157. @available(iOS 10, *)
  158. extension AppDelegate : UNUserNotificationCenterDelegate {
  159. // Receive displayed notifications for iOS 10 devices.
  160. func userNotificationCenter(_ center: UNUserNotificationCenter,
  161. willPresent notification: UNNotification,
  162. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  163. let userInfo = notification.request.content.userInfo
  164. // With swizzling disabled you must let Messaging know about the message, for Analytics
  165. // Messaging.messaging().appDidReceiveMessage(userInfo)
  166. // Print message ID.
  167. // if let messageID = userInfo[gcmMessageIDKey] {
  168. // print("Message ID: \(messageID)")
  169. // }
  170. // Print full message.
  171. print(userInfo)
  172. // Change this to your preferred presentation option
  173. completionHandler([[.alert, .sound]])
  174. }
  175. func userNotificationCenter(_ center: UNUserNotificationCenter,
  176. didReceive response: UNNotificationResponse,
  177. withCompletionHandler completionHandler: @escaping () -> Void) {
  178. let userInfo = response.notification.request.content.userInfo
  179. // Print message ID.
  180. // if let messageID = userInfo[gcmMessageIDKey] {
  181. // print("Message ID: \(messageID)")
  182. // }
  183. // With swizzling disabled you must let Messaging know about the message, for Analytics
  184. // Messaging.messaging().appDidReceiveMessage(userInfo)
  185. // Print full message.
  186. print(userInfo)
  187. // notif handler : open noti list page
  188. if let tabBarController = self.window?.rootViewController as? UITabBarController {
  189. tabBarController.selectedViewController?.performSegue(withIdentifier: "NotifListSegueId", sender: tabBarController.selectedViewController.self)
  190. }
  191. // tell the app that we have finished processing the user’s action / response
  192. completionHandler()
  193. }
  194. }
  195. // [END ios_10_message_handling]
  196. extension AppDelegate : MessagingDelegate {
  197. // [START refresh_token]
  198. func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
  199. print("Firebase registration token: \(String(describing: fcmToken))")
  200. if let token = fcmToken {
  201. self.postFcmToken(fcmToken: token)
  202. }
  203. let dataDict:[String: String] = ["token": fcmToken ?? ""]
  204. NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
  205. // TODO: If necessary send token to application server.
  206. // Note: This callback is fired at each app startup and whenever a new token is generated.
  207. }
  208. // [END refresh_token]
  209. }
  210. extension AppDelegate {
  211. private func postFcmToken(fcmToken: String) {
  212. let isLogin = UserState.instance.isLoggedIn()
  213. if isLogin {
  214. let userId = UserState.instance.getUserId()
  215. let roleId = UserState.instance.getRoleId()
  216. SiraniApiServices().postFcmToken(user_id: userId, role_id: roleId, fcmToken: fcmToken).responseJSON { response in
  217. if response.error == nil {
  218. print("FCM User Token Updated To Server : \(fcmToken)")
  219. }
  220. }
  221. }
  222. }
  223. }