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.

316 lines
10 KiB

6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 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 Fabric
  16. import Crashlytics
  17. import AlamofireNetworkActivityLogger
  18. import IQKeyboardManagerSwift
  19. import LGSideMenuController
  20. import Localize_Swift
  21. import ChannelIO
  22. let server: Server = .kftcTest
  23. var overlayView: UIView?
  24. @UIApplicationMain
  25. class AppDelegate: UIResponder, UIApplicationDelegate {
  26. var window: UIWindow?
  27. func application(
  28. _ application: UIApplication,
  29. didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
  30. ) -> Bool {
  31. UIApplication.shared.applicationIconBadgeNumber = 0
  32. NetworkActivityLogger.shared.startLogging()
  33. NetworkActivityLogger.shared.level = .debug
  34. IQKeyboardManager.shared.enable = true
  35. IQKeyboardManager.shared.shouldResignOnTouchOutside = true
  36. FirebaseApp.configure()
  37. Fabric.with([Crashlytics.self])
  38. Fabric.sharedSDK().debug = true
  39. Messaging.messaging().delegate = self
  40. let center = UNUserNotificationCenter.current()
  41. center.delegate = self
  42. center.requestAuthorization(options: [.alert, .sound, .badge]) { (_, _) in}
  43. application.registerForRemoteNotifications()
  44. print("FCM Token: \(Messaging.messaging().fcmToken ?? "nil")")
  45. // Initialize ChannelIO
  46. ChannelIO.initialize()
  47. setUUID()
  48. setupNavBar()
  49. setEntryPoint()
  50. UserDefaults.standard.removeObject(forKey: AppConstants.isOpenedTokenRenwalAlert)
  51. UserDefaults.standard.removeObject(forKey: AppConstants.isOpenedPopupNotification)
  52. return true
  53. }
  54. func application(
  55. _ application: UIApplication,
  56. didReceiveRemoteNotification userInfo: [AnyHashable: Any]
  57. ) { }
  58. func application(
  59. _ application: UIApplication,
  60. didReceiveRemoteNotification userInfo: [AnyHashable: Any],
  61. fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
  62. ) {
  63. ChannelIO.handlePushNotification(userInfo) {
  64. completionHandler(.noData)
  65. }
  66. }
  67. func application(
  68. _ application: UIApplication,
  69. didFailToRegisterForRemoteNotificationsWithError error: Error
  70. ) { }
  71. func application(
  72. _ application: UIApplication,
  73. didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
  74. ) {
  75. let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
  76. print("APNs device token: \(deviceTokenString)")
  77. Messaging.messaging().apnsToken = deviceToken
  78. ChannelIO.initPushToken(deviceToken: deviceToken)
  79. }
  80. func applicationDidEnterBackground(_ application: UIApplication) {
  81. let store = UserDefaults.standard
  82. let language = Localize.currentLanguage()
  83. store.set(language, forKey: AppConstants.currentLanguage)
  84. let viewcontroller = UIViewController()
  85. viewcontroller.view.backgroundColor = AppConstants.themeRedColor
  86. viewcontroller.view.frame = UIScreen.main.bounds
  87. overlayView = viewcontroller.view
  88. guard let view = overlayView else {return}
  89. let topView = UIApplication.shared.keyWindow?.subviews.last
  90. topView?.addSubview(view)
  91. topView?.bringSubview(toFront: view)
  92. }
  93. func applicationWillEnterForeground(_ application: UIApplication) {
  94. if let language = UserDefaults.standard.string(forKey: AppConstants.currentLanguage) {
  95. Localize.setCurrentLanguage(language)
  96. }
  97. overlayView?.removeFromSuperview()
  98. }
  99. }
  100. // MARK: - Other Functions
  101. extension AppDelegate {
  102. private func setUUID() {
  103. if UserDefaults.standard.string(forKey: AppConstants.uuid) == nil {
  104. let uuid = UUID().uuidString
  105. UserDefaults.standard.set(uuid, forKey: AppConstants.uuid)
  106. }
  107. }
  108. private func setupNavBar() {
  109. let appearance = UINavigationBar.appearance()
  110. appearance.backIndicatorImage = #imageLiteral(resourceName: "backIconBlack")
  111. appearance.backIndicatorTransitionMaskImage = #imageLiteral(resourceName: "backIconBlack")
  112. appearance.tintColor = UIColor.black
  113. }
  114. private func setEntryPoint() {
  115. guard let _ = KeyChain.shared.get(key: .email),
  116. (KeyChain.shared.get(key: .login) ?? "1") == "1" ? true : false else {
  117. self.goSplashScreen()
  118. return
  119. }
  120. let biometricAuthenticationWireframe = BiometricAuthenticationWireframe()
  121. biometricAuthenticationWireframe.openWithDelegate(
  122. on: self.window!,
  123. delegate: self
  124. )
  125. }
  126. private func doLogin(){
  127. self.window?.rootViewController?.showProgressHud()
  128. let loginService = LoginService()
  129. guard let userID = KeyChain.shared.get(key: .email),
  130. let password = KeyChain.shared.get(key: .password) else {
  131. self.goSplashScreen()
  132. return
  133. }
  134. loginService._login(
  135. userId: userID,
  136. password: password,
  137. success: { (user) in
  138. let accessCode = user?.accessCode ?? ""
  139. let accessCodeBase64 = accessCode
  140. Utility.save(user: user, accessCodeBase64: accessCodeBase64, password: password, login: true)
  141. let mainWireFrame = MainWireframe.shared
  142. let tabBarViewController = mainWireFrame?.getMainView()
  143. let sidemenuVc = UIStoryboard(name: "SideMenu", bundle: nil).instantiateViewController(withIdentifier: "SideMenuViewController") as! SideMenuViewController
  144. let sideMenuController = LGSideMenuController(rootViewController: tabBarViewController, leftViewController: sidemenuVc, rightViewController: nil)
  145. sideMenuController.rootViewLayerShadowColor = UIColor(white: 0.9, alpha: 0.6)
  146. sideMenuController.rootViewLayerShadowRadius = 8.0
  147. sideMenuController.leftViewPresentationStyle = .scaleFromBig
  148. sideMenuController.leftViewWidth = UIScreen.main.bounds.width - 70.0
  149. if #available(iOS 10.0, *) {
  150. sideMenuController.leftViewBackgroundBlurEffect = UIBlurEffect(style: .regular)
  151. } else {
  152. // Fallback on earlier versions
  153. }
  154. self.window?.rootViewController?.hideProgressHud()
  155. self.window?.backgroundColor = sidemenuVc.view.backgroundColor
  156. self.window?.rootViewController = sideMenuController
  157. }) { (error) in
  158. self.window?.rootViewController?.hideProgressHud()
  159. self.window?.rootViewController?.alert(type: .error, message: error.localizedDescription, title: "Warning"){
  160. // if failed login, remove all in keychain, change logout status and then go splash screen
  161. KeyChain.shared.removeAll()
  162. self.goSplashScreen()
  163. }
  164. }
  165. }
  166. private func goSplashScreen() {
  167. let splashWireframe = SplashScreenWireframe()
  168. let nav = UINavigationController.init(rootViewController: splashWireframe.getMainView())
  169. self.window?.rootViewController = nav
  170. }
  171. }
  172. // MARK: - UNUserNotificationCenterDelegate
  173. extension AppDelegate: UNUserNotificationCenterDelegate {
  174. func userNotificationCenter(
  175. _ center: UNUserNotificationCenter,
  176. willPresent notification: UNNotification,
  177. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
  178. ) {
  179. let userInfo = notification.request.content.userInfo
  180. print("Message ID: \(userInfo["gcm_message_id"] ?? "nil")")
  181. completionHandler([
  182. UNNotificationPresentationOptions.alert,
  183. UNNotificationPresentationOptions.sound,
  184. UNNotificationPresentationOptions.badge
  185. ])
  186. }
  187. func userNotificationCenter(
  188. _ center: UNUserNotificationCenter,
  189. didReceive response: UNNotificationResponse,
  190. withCompletionHandler completionHandler: @escaping () -> Void
  191. ) {
  192. let userInfo = response.notification.request.content.userInfo
  193. print("Message ID: \(userInfo["gcm_message_id"] ?? "nil")")
  194. if ChannelIO.isChannelPushNotification(userInfo) {
  195. ChannelIO.handlePushNotification(userInfo)
  196. }
  197. print(userInfo)
  198. completionHandler()
  199. }
  200. }
  201. // MARK: - MessagingDelegate
  202. extension AppDelegate: MessagingDelegate {
  203. func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
  204. print("Firebase registration token: \(fcmToken)")
  205. let userInfo = ["token": fcmToken]
  206. NotificationCenter.default.post(
  207. name: Notification.Name("FCMToken"),
  208. object: nil,
  209. userInfo: userInfo
  210. )
  211. }
  212. func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
  213. print("Received data message: \(remoteMessage.appData)")
  214. }
  215. }
  216. // MARK: - BiometricAuthenticationViewControllerDelegate
  217. extension AppDelegate: BiometricAuthenticationViewControllerDelegate{
  218. func viewController(_ viewController: BiometricAuthenticationViewController, informationTitleLabel titleLabel: UILabel, authenticationButton button: UIButton) {
  219. titleLabel.text = "bio_login_intro_text".localized()
  220. button.setTitle("login_text".localized(), for: .normal)
  221. }
  222. func didComplete(_ viewController: BiometricAuthenticationViewController) {
  223. self.doLogin()
  224. }
  225. func viewController(
  226. _ viewController: BiometricAuthenticationViewController,
  227. didFailWithError error: BiometricAuthenticationError,
  228. errorMessage: String?
  229. ) {
  230. print("BiometricAuthenticationWireframe Error: \(errorMessage ?? "")")
  231. // if don't use biometric authentication or user press password
  232. DispatchQueue.main.async {
  233. switch error {
  234. case .biometryNotAvailable, .userFallback:
  235. let secureKeypad = SecureKeypad(target: viewController)
  236. secureKeypad.delegate = self
  237. secureKeypad.present(animated: true)
  238. case .notBeConfigured, .biometryNotEnrolled:
  239. viewController.alert(type: .error, message: error.message)
  240. default:
  241. break
  242. }
  243. }
  244. }
  245. func doSelectLocalAuthenticationPolicy(_ viewController: BiometricAuthenticationViewController) -> BiometricAuthenticationPolicy {
  246. return .deviceOwnerAuthenticationWithBiometrics
  247. }
  248. }
  249. // MARK: - SecureKeypadDelegate
  250. extension AppDelegate: SecureKeypadDelegate {
  251. func didComplete(_ encryptedString: String) {
  252. if encryptedString != "" {
  253. KeyChain.shared.save(data: encryptedString, key: .password)
  254. self.doLogin()
  255. }
  256. }
  257. }