You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

422 lines
14 KiB

6 years ago
6 years ago
3 years ago
6 years ago
1 year ago
1 year ago
6 years ago
6 years ago
6 years ago
4 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. //
  2. // AppDelegate.swift
  3. // GMERemittance
  4. //
  5. // Created by Fm-user on 11/30/17.
  6. // Copyright © 2017 Gobal Money Express Co. Ltd. All rights reserved.
  7. //
  8. import UIKit
  9. import Firebase
  10. import FirebaseAuth
  11. import UserNotifications
  12. import FirebaseInstanceID
  13. import FirebaseMessaging
  14. import BRYXBanner
  15. import AlamofireNetworkActivityLogger
  16. import IQKeyboardManagerSwift
  17. import Localize_Swift
  18. import LGSideMenuController
  19. import FirebaseCore
  20. #if DEBUG
  21. var server: Server = .live
  22. #else
  23. var server: Server = .live
  24. #endif
  25. var destination: PushNotificationDestination?
  26. var overlayView: UIView?
  27. enum PushNotificationDestination {
  28. case trasactionHistory
  29. case pushNotification
  30. static func getDestination(target: String) -> PushNotificationDestination? {
  31. switch target {
  32. case "TransactionHistory":
  33. return .trasactionHistory
  34. case "PushNotification":
  35. return .pushNotification
  36. default:
  37. return nil
  38. }
  39. }
  40. }
  41. enum PushNotificationAction {
  42. case notifictaion
  43. case notice
  44. case renewID
  45. case sendMoney
  46. case howToDeposit
  47. case redirect
  48. static func getAction(target: String) -> PushNotificationAction? {
  49. switch target {
  50. case "OPEN_ACTIVITY_NOTIFICATION":
  51. return .notifictaion
  52. case "OPEN_ACTIVITY_NOTICE":
  53. return .notice
  54. case "OPEN_ACTIVITY_RENEW_ID":
  55. return .renewID
  56. case "OPEN_ACTIVITY_SENDMONEY":
  57. return .sendMoney
  58. case "OPEN_ACTIVITY_HOW_TO_DEPOSIT":
  59. return .howToDeposit
  60. case "OPEN_ACTIVITY_REDIRECT":
  61. return .redirect
  62. default:
  63. return nil
  64. }
  65. }
  66. }
  67. @UIApplicationMain
  68. class AppDelegate: UIResponder, UIApplicationDelegate {
  69. var window: UIWindow?
  70. func application(
  71. _ application: UIApplication,
  72. didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  73. ) -> Bool {
  74. UIApplication.shared.applicationIconBadgeNumber = 0
  75. #if DEBUGx2
  76. NetworkActivityLogger.shared.startLogging()
  77. NetworkActivityLogger.shared.level = .debug
  78. #endif
  79. IQKeyboardManager.shared.enable = true
  80. IQKeyboardManager.shared.shouldResignOnTouchOutside = true
  81. IQKeyboardManager.shared.toolbarTintColor = .black
  82. FirebaseApp.configure()
  83. Messaging.messaging().delegate = self
  84. // let center = UNUserNotificationCenter.current()
  85. // center.delegate = self
  86. // center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, _) in
  87. //
  88. // guard granted else { return }
  89. //
  90. // center.getNotificationSettings { settings in
  91. // print("Notification settings: \(settings)")
  92. // DispatchQueue.main.async {
  93. // UIApplication.shared.registerForRemoteNotifications()
  94. // }
  95. // }
  96. // }
  97. if #available(iOS 15, *) {
  98. let appearance = UINavigationBarAppearance()
  99. appearance.configureWithOpaqueBackground()
  100. UINavigationBar.appearance().standardAppearance = appearance
  101. UINavigationBar.appearance().scrollEdgeAppearance = appearance
  102. }
  103. if #available(iOS 10.0, *) {
  104. // For iOS 10 display notification (sent via APNS)
  105. UNUserNotificationCenter.current().delegate = self
  106. let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
  107. UNUserNotificationCenter.current().requestAuthorization(
  108. options: authOptions,
  109. completionHandler: { _, _ in }
  110. )
  111. } else {
  112. let settings: UIUserNotificationSettings =
  113. UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
  114. application.registerUserNotificationSettings(settings)
  115. }
  116. application.registerForRemoteNotifications()
  117. // Move push notification's destination
  118. let useInfo = launchOptions?[.remoteNotification] as? [String: AnyObject]
  119. destination = extractDestination(userInfo: useInfo)
  120. self.window?.rootViewController = LauncherScreenWireframe().getMainView()
  121. if #available(iOS 13.0, *) {
  122. window?.overrideUserInterfaceStyle = .light
  123. }
  124. GMEDB
  125. .shared
  126. .app
  127. .remove([.isOpenedTokenRenwalAlert, .isOpenedPopupNotification])
  128. StoreReviewHelper.shared.incrementAppOpenedCount()
  129. //Default "Back title is removed"
  130. let barButtonItemAppearance = UIBarButtonItem.appearance()
  131. barButtonItemAppearance.setBackButtonTitlePositionAdjustment(UIOffset(horizontal: -1000, vertical: 0), for:UIBarMetrics.default)
  132. return true
  133. }
  134. func application(
  135. _ application: UIApplication,
  136. didReceiveRemoteNotification userInfo: [AnyHashable: Any]
  137. ) { }
  138. func application(
  139. _ application: UIApplication,
  140. didReceiveRemoteNotification userInfo: [AnyHashable: Any],
  141. fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
  142. ) {
  143. }
  144. func application(
  145. _ application: UIApplication,
  146. didFailToRegisterForRemoteNotificationsWithError error: Error
  147. ) { }
  148. func application(
  149. _ application: UIApplication,
  150. didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
  151. ) {
  152. let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
  153. print("APNs device token: \(deviceTokenString)")
  154. Messaging.messaging().apnsToken = deviceToken
  155. }
  156. func applicationDidEnterBackground(_ application: UIApplication) {
  157. let taskID = application.beginBackgroundTask(expirationHandler: nil)
  158. let language = Localize.currentLanguage()
  159. GMEDB.shared.app.set(language, .currentLanguage)
  160. let viewcontroller = UIViewController()
  161. viewcontroller.view.backgroundColor = .themeRed
  162. viewcontroller.view.frame = UIScreen.main.bounds
  163. overlayView = viewcontroller.view
  164. guard let view = overlayView else {return}
  165. let topView = UIApplication.shared.keyWindow?.subviews.last
  166. topView?.addSubview(view)
  167. topView?.bringSubviewToFront(view)
  168. if taskID != UIBackgroundTaskIdentifier.invalid {
  169. UIApplication.shared.endBackgroundTask(taskID)
  170. }
  171. }
  172. func applicationWillEnterForeground(_ application: UIApplication) {
  173. if let language = GMEDB.shared.app.string(.currentLanguage) {
  174. Localize.setCurrentLanguage(language)
  175. }
  176. overlayView?.removeFromSuperview()
  177. }
  178. func application(
  179. _ app: UIApplication,
  180. open url: URL,
  181. options: [UIApplication.OpenURLOptionsKey : Any] = [:]
  182. ) -> Bool {
  183. return true
  184. }
  185. }
  186. // MARK: - UNUserNotificationCenterDelegate
  187. extension AppDelegate: UNUserNotificationCenterDelegate {
  188. func userNotificationCenter(
  189. _ center: UNUserNotificationCenter,
  190. willPresent notification: UNNotification,
  191. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
  192. ) {
  193. let userInfo = notification.request.content.userInfo
  194. print("Message ID: \(userInfo["gcm_message_id"] ?? "nil")")
  195. print(userInfo)
  196. completionHandler([
  197. UNNotificationPresentationOptions.alert,
  198. UNNotificationPresentationOptions.sound,
  199. UNNotificationPresentationOptions.badge
  200. ])
  201. }
  202. func userNotificationCenter(
  203. _ center: UNUserNotificationCenter,
  204. didReceive response: UNNotificationResponse,
  205. withCompletionHandler completionHandler: @escaping () -> Void
  206. ) {
  207. let userInfo = response.notification.request.content.userInfo
  208. print("Message ID: \(userInfo["gcm_message_id"] ?? "nil")")
  209. print(userInfo)
  210. if let action = extractClickAction(userInfo: userInfo as? [String: AnyObject]) {
  211. let baseVC = window?.rootViewController?.presentedViewController ?? window?.rootViewController
  212. DispatchQueue.main.async { [self] in
  213. switch action {
  214. case .notifictaion:
  215. if (KeyChain.shared.get(key: .login) ?? "0") == "0" {
  216. DispatchQueue.main.asyncAfter(deadline: .now() + 0.4, execute: {
  217. let splashWireframe = SplashScreenWireframe()
  218. let splashViewController = splashWireframe.getMainView()
  219. let nav = UINavigationController(rootViewController: splashViewController)
  220. self.window?.rootViewController = nav
  221. })
  222. if #available(iOS 13.0, *) {
  223. window?.overrideUserInterfaceStyle = .light
  224. }
  225. } else {
  226. NotificationListWireframe().open(on: baseVC)
  227. }
  228. case .notice:
  229. NotificationHistoryWireframe().open(on: baseVC)
  230. case .renewID:
  231. RenewIDWireframe().open(on: baseVC)
  232. case .sendMoney:
  233. RecipientsWireframe().open(on: baseVC)
  234. case .howToDeposit:
  235. HowToDepositWireframe().open(on: baseVC)
  236. case .redirect:
  237. // break
  238. self.openURL(userInfo: userInfo as? [String: AnyObject])
  239. }
  240. }
  241. }
  242. // open push notification's destination
  243. guard
  244. window?.rootViewController is LGSideMenuController,
  245. let destination = extractDestination(userInfo: userInfo as? [String: AnyObject]) else {
  246. completionHandler()
  247. return
  248. }
  249. let baseVC = window?.rootViewController?.presentedViewController ?? window?.rootViewController
  250. DispatchQueue.main.async {
  251. switch destination {
  252. case .trasactionHistory:
  253. TransactionHistoryGroupWireframe().open(overseasType: .inbound, on: baseVC)
  254. case .pushNotification:
  255. NotificationHistoryWireframe().open(on: baseVC)
  256. }
  257. }
  258. completionHandler()
  259. }
  260. func openURL(userInfo: [String : AnyObject]?) {
  261. guard
  262. let url = userInfo?["url"] as? String else {
  263. return
  264. }
  265. guard let webController = UIStoryboard(name: "Storyboard", bundle: nil)
  266. .instantiateViewController(withIdentifier: "WebLinksViewController") as? WebLinksViewController
  267. else { return }
  268. // webController.titleString = item.title ?? "Notification"
  269. webController.url = url
  270. let nav = UINavigationController.init(rootViewController: webController)
  271. // let rootViewController = self.window.rootViewController as! UINavigationController
  272. // rootViewController.pushViewController(nav, animated: true)
  273. // If this scene's self.window is nil then set a new UIWindow object to it.
  274. window = window ?? UIWindow()
  275. // Set this scene's window's background color.
  276. self.window!.backgroundColor = UIColor.red
  277. // Create a ViewController object and set it as the scene's window's root view controller.
  278. // let rootViewController = self.window!.rootViewController as! UINavigationController
  279. self.window?.rootViewController?.present(nav, animated: true)
  280. // rootViewController.pushViewController(nav, animated: true)
  281. // Make this scene's window be visible.
  282. // self.window!.makeKeyAndVisible()
  283. // guard scene is UIWindowScene else { return }
  284. // NotificationHistoryWireframe().open(on: nav)
  285. }
  286. }
  287. extension AppDelegate {
  288. private func extractDestination(userInfo: [String : AnyObject]?) -> PushNotificationDestination? {
  289. guard
  290. let destination = userInfo?["destination"] as? String,
  291. let destinationType = PushNotificationDestination.getDestination(target: destination) else {
  292. return nil
  293. }
  294. return destinationType
  295. }
  296. private func extractClickAction(userInfo: [String : AnyObject]?) -> PushNotificationAction? {
  297. guard
  298. let aps = userInfo?["aps"] as? [String: AnyObject],
  299. let destination = aps["category"] as? String,
  300. let destinationType = PushNotificationAction.getAction(target: destination) else {
  301. return nil
  302. }
  303. return destinationType
  304. }
  305. private func urlClickAction(userInfo: [String : AnyObject]?) -> PushNotificationAction? {
  306. guard
  307. let aps = userInfo?["aps"] as? [String: AnyObject],
  308. let destination = aps["category"] as? String,
  309. let destinationType = PushNotificationAction.getAction(target: destination) else {
  310. return nil
  311. }
  312. return destinationType
  313. }
  314. }
  315. extension AppDelegate{
  316. func setNewRootViewController(rootVC: UIViewController){
  317. let frame = UIScreen.main.bounds
  318. self.window = UIWindow(frame: frame)
  319. if let window = self.window {
  320. window.backgroundColor = .white
  321. window.rootViewController = rootVC
  322. window.makeKeyAndVisible()
  323. }
  324. }
  325. func reload(){
  326. let vc = LauncherScreenWireframe().getMainView()
  327. self.setNewRootViewController(rootVC: vc)
  328. }
  329. }
  330. // MARK: - MessagingDelegate
  331. extension AppDelegate: MessagingDelegate {
  332. func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
  333. print("Firebase registration token: \(fcmToken)")
  334. let userInfo = ["token": fcmToken]
  335. NotificationCenter.default.post(
  336. name: Notification.Name("FCMToken"),
  337. object: nil,
  338. userInfo: userInfo
  339. )
  340. }
  341. func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
  342. print("Received data message: \(remoteMessage.appData)")
  343. }
  344. }
  345. let appDelegate = UIApplication.shared.delegate as! AppDelegate