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.

318 lines
12 KiB

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
5 years ago
6 years ago
6 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. let server: Server = .stagging
  22. var overlayView: UIView?
  23. @UIApplicationMain
  24. class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
  25. var window: UIWindow?
  26. let gcmMessageIDKey = "gcm_message_id"
  27. var firstTranscationStatusForHome:Bool?
  28. var firstTranscationStatusForProfileForm:Bool?
  29. var cmRegistrationId: String?
  30. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  31. UIApplication.shared.applicationIconBadgeNumber = 0
  32. firstTranscationStatusForHome = true
  33. firstTranscationStatusForProfileForm = true
  34. NetworkActivityLogger.shared.startLogging()
  35. NetworkActivityLogger.shared.level = .debug
  36. IQKeyboardManager.shared.enable = true
  37. IQKeyboardManager.shared.shouldResignOnTouchOutside = true
  38. FirebaseApp.configure()
  39. Fabric.with([Crashlytics.self])
  40. Fabric.sharedSDK().debug = true
  41. Messaging.messaging().delegate = self
  42. registerForNotification(application: application)
  43. setUUID()
  44. setupNavBar()
  45. setupStatusBar()
  46. setEntryPoint()
  47. isetupLanguage()
  48. if #available(iOS 10.0, *) {
  49. UNUserNotificationCenter.current().delegate = self
  50. } else {
  51. // Fallback on earlier versions
  52. }
  53. return true
  54. }
  55. private func isetupLanguage() {
  56. let language = UserDefaults.standard.string(forKey: AppConstants.currentLanguage)
  57. if (language != nil), let preferedDeviceLanguage = Locale.preferredLanguages.elementAt(index: 0), let _ = preferedDeviceLanguage.components(separatedBy: "-").first {
  58. Localize.setCurrentLanguage(language ?? "en")
  59. }
  60. }
  61. private func setUUID() {
  62. if UserDefaults.standard.string(forKey: AppConstants.uuid) == nil {
  63. let uuid = UUID().uuidString
  64. UserDefaults.standard.set(uuid, forKey: AppConstants.uuid)
  65. }
  66. }
  67. private func setupStatusBar() {
  68. // let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
  69. // if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
  70. // statusBar.backgroundColor = UIColor.blue
  71. // }
  72. }
  73. private func setupNavBar() {
  74. let appearance = UINavigationBar.appearance()
  75. appearance.backIndicatorImage = #imageLiteral(resourceName: "backIconBlack")
  76. appearance.backIndicatorTransitionMaskImage = #imageLiteral(resourceName: "backIconBlack")
  77. appearance.tintColor = UIColor.black
  78. }
  79. private func setEntryPoint() {
  80. // check user status
  81. guard let _ = KeyChain.shared.get(key: .email),
  82. (KeyChain.shared.get(key: .login) ?? "1") == "1" ? true : false else {
  83. self.goSplashScreen()
  84. return
  85. }
  86. let biometricAuthenticationWireframe = BiometricAuthenticationWireframe()
  87. biometricAuthenticationWireframe.openWithDelegate(
  88. on: self.window!,
  89. delegate: self
  90. )
  91. }
  92. private func registerForNotification(application: UIApplication) {
  93. let settings: UIUserNotificationSettings =
  94. UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
  95. application.registerForRemoteNotifications()
  96. application.registerUserNotificationSettings(settings)
  97. }
  98. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  99. if userInfo[gcmMessageIDKey] != nil {
  100. }
  101. }
  102. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
  103. fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  104. }
  105. func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
  106. cmRegistrationId = fcmToken
  107. print(fcmToken)
  108. }
  109. func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
  110. print(remoteMessage.appData)
  111. }
  112. public func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
  113. }
  114. @available(iOS 10.0, *)
  115. func userNotificationCenter(_ center: UNUserNotificationCenter,
  116. willPresent notification: UNNotification,
  117. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  118. // var userInfo = notification.request.content.userInfo
  119. // if let aps = userInfo["aps"] as? NSDictionary,
  120. // let alert = aps["alert"] as? NSDictionary,
  121. // let body = alert["body"] as? String,
  122. // let title = alert["title"] as? String {
  123. // let image = UIImage.init(named: "ic_gme")
  124. // let banner = Banner(title: title, subtitle: body, image: image, backgroundColor: UIColor(red:0.93, green:0.11, blue:0.14, alpha:1.0))
  125. // banner.show(duration: 5.0)
  126. // }
  127. completionHandler(
  128. [UNNotificationPresentationOptions.alert,
  129. UNNotificationPresentationOptions.sound,
  130. UNNotificationPresentationOptions.badge])
  131. }
  132. func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  133. // print("Unable to register for remote notifications: \(error.localizedDescription)")
  134. }
  135. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  136. }
  137. /**
  138. method for redirection of page when push notification tap
  139. */
  140. func applicationDidEnterBackground(_ application: UIApplication) {
  141. let store = UserDefaults.standard
  142. let language = Localize.currentLanguage()
  143. store.set(language, forKey: AppConstants.currentLanguage)
  144. let viewcontroller = UIViewController()
  145. viewcontroller.view.backgroundColor = AppConstants.themeRedColor
  146. viewcontroller.view.frame = UIScreen.main.bounds
  147. overlayView = viewcontroller.view
  148. guard let view = overlayView else {return}
  149. let topView = UIApplication.shared.keyWindow?.subviews.last
  150. topView?.addSubview(view)
  151. topView?.bringSubview(toFront: view)
  152. }
  153. func applicationWillEnterForeground(_ application: UIApplication) {
  154. if let language = UserDefaults.standard.string(forKey: AppConstants.currentLanguage) {
  155. Localize.setCurrentLanguage(language)
  156. }
  157. overlayView?.removeFromSuperview()
  158. }
  159. private func doLogin(){
  160. self.window?.rootViewController?.showProgressHud()
  161. let loginService = LoginService()
  162. guard let userID = KeyChain.shared.get(key: .email),
  163. let password = KeyChain.shared.get(key: .password) else {
  164. self.goSplashScreen()
  165. return
  166. }
  167. loginService._login(
  168. userId: userID,
  169. password: password,
  170. success: { (user) in
  171. let accessCode = user?.accessCode ?? ""
  172. let accessCodeBase64 = accessCode
  173. Utility.save(user: user, accessCodeBase64: accessCodeBase64, password: password, login: true)
  174. let mainWireFrame = MainWireframe.shared
  175. let tabBarViewController = mainWireFrame?.getMainView()
  176. let sidemenuVc = UIStoryboard(name: "SideMenu", bundle: nil).instantiateViewController(withIdentifier: "SideMenuViewController") as! SideMenuViewController
  177. let sideMenuController = LGSideMenuController(rootViewController: tabBarViewController, leftViewController: sidemenuVc, rightViewController: nil)
  178. sideMenuController.rootViewLayerShadowColor = UIColor(white: 0.9, alpha: 0.6)
  179. sideMenuController.rootViewLayerShadowRadius = 8.0
  180. sideMenuController.leftViewPresentationStyle = .scaleFromBig
  181. sideMenuController.leftViewWidth = UIScreen.main.bounds.width - 70.0
  182. if #available(iOS 10.0, *) {
  183. sideMenuController.leftViewBackgroundBlurEffect = UIBlurEffect(style: .regular)
  184. } else {
  185. // Fallback on earlier versions
  186. }
  187. self.window?.rootViewController?.hideProgressHud()
  188. self.window?.backgroundColor = sidemenuVc.view.backgroundColor
  189. self.window?.rootViewController = sideMenuController
  190. }) { (error) in
  191. self.window?.rootViewController?.hideProgressHud()
  192. self.window?.rootViewController?.alert(message: error.localizedDescription, title: "Warning"){
  193. // if failed login, remove all in keychain, change logout status and then go splash screen
  194. KeyChain.shared.removeAll()
  195. self.goSplashScreen()
  196. }
  197. }
  198. }
  199. private func goSplashScreen() {
  200. let splashWireframe = SplashScreenWireframe()
  201. let nav = UINavigationController.init(rootViewController: splashWireframe.getMainView())
  202. self.window?.rootViewController = nav
  203. }
  204. }
  205. // MARK: - BiometricAuthenticationViewControllerDelegate
  206. extension AppDelegate: BiometricAuthenticationViewControllerDelegate{
  207. func viewController(_ viewController: BiometricAuthenticationViewController, informationTitleLabel titleLabel: UILabel) {
  208. titleLabel.text = "Please enter authentication information for login"
  209. }
  210. func didComplete(_ viewController: BiometricAuthenticationViewController) {
  211. self.doLogin()
  212. }
  213. func viewController(_ viewController: BiometricAuthenticationViewController, didFailWithError error: Error, errorMessage: String?) {
  214. print("BiometricAuthenticationWireframe Error: \(errorMessage ?? "")")
  215. // if don't use biometric authentication or user press password
  216. DispatchQueue.main.async {
  217. if let error = error as? BiometricAuthenticationError {
  218. switch error {
  219. case .biometryNotAvailable, .userFallback:
  220. let secureKeypad = SecureKeypad(target: viewController)
  221. secureKeypad.title = "Password of your account"
  222. secureKeypad.placeholder = "Enter your password for login"
  223. secureKeypad.placeholderFont = UIFont(name: "Arial", size: 15)
  224. secureKeypad.delegate = self
  225. secureKeypad.present(animated: true)
  226. default:
  227. break
  228. }
  229. }
  230. }
  231. }
  232. func doSelectLocalAuthenticationPolicy(_ viewController: BiometricAuthenticationViewController) -> BiometricAuthenticationPolicy{
  233. return .deviceOwnerAuthenticationWithBiometrics
  234. }
  235. }
  236. // MARK: - SecureKeypadDelegate
  237. extension AppDelegate: SecureKeypadDelegate {
  238. func didComplete(_ encryptedString: String) {
  239. if encryptedString != "" {
  240. KeyChain.shared.save(data: encryptedString, key: .password)
  241. self.doLogin()
  242. }
  243. }
  244. }