AppDelegate.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. //
  2. // AppDelegate.swift
  3. // rrr
  4. //
  5. // Created by Muchinfo on 2020/12/28.
  6. //
  7. import UIKit
  8. import CoreData
  9. import IQKeyboardManagerSwift
  10. import HandyJSON
  11. import Bugly
  12. import WHToast
  13. import NVActivityIndicatorView
  14. @UIApplicationMain
  15. class AppDelegate: UIResponder, UIApplicationDelegate {
  16. // MARK: - 属性列表
  17. /// 是否允许横屏
  18. var isRotation: Bool = false
  19. /// window
  20. var window: UIWindow?
  21. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  22. // Override point for customization after application launch.
  23. /// 配置底层单例实例化
  24. let businessCore = MTP2BusinessCore.shared
  25. businessCore.delegate = self
  26. /// 初始化数据库
  27. DatabaseHelper.firstOpenInitialData()
  28. ///第三方收起键盘
  29. IQKeyboardManager.shared.enable = true
  30. IQKeyboardManager.shared.enableAutoToolbar = true
  31. IQKeyboardManager.shared.shouldResignOnTouchOutside = true
  32. /// 全局配置字段解析忽略大小写
  33. HandyJSONConfiguration.deserializeOptions = .caseInsensitive
  34. /// Bugly配置
  35. initBugly()
  36. /// 判断其是否第一次启动
  37. if UserDefaultsUtils.isFirstOpen() {
  38. /// 系统设置字体大小
  39. UserDefaultsUtils.setFontSize(1.0)
  40. /// 默认登录时间有效期
  41. UserDefaultsUtils.setPwdDown(8)
  42. }
  43. /// 修改第一次运行状态标志
  44. UserDefaultsUtils.setOpened()
  45. return true
  46. }
  47. func applicationWillResignActive(_ application: UIApplication) {
  48. // 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.
  49. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  50. }
  51. func applicationDidEnterBackground(_ application: UIApplication) {
  52. // 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.
  53. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  54. // application
  55. saveContext()
  56. }
  57. func applicationWillEnterForeground(_ application: UIApplication) {
  58. // 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.
  59. }
  60. func applicationDidBecomeActive(_ application: UIApplication) {
  61. // 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.
  62. }
  63. func applicationWillTerminate(_ application: UIApplication) {
  64. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  65. saveContext()
  66. }
  67. func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  68. }
  69. func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  70. if url.host == "safepay" {
  71. /// 跳转支付宝钱包进行支付,处理支付结果
  72. AlipaySDK.defaultService().processOrder(withPaymentResult: url) { result in
  73. dPrint("-------\(String(describing: result))")
  74. DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
  75. /// 支付失败
  76. if let rs = result,
  77. (rs as NSDictionary)["resultStatus"] as? String != "9000" {
  78. let msg = (rs as NSDictionary)["memo"] as? String
  79. WHToast.showMessage("支付失败,原因:\(msg ?? "请稍候查看单据信息")", duration: ToastTimer, finishHandler: {})
  80. } else {
  81. WHToast.showSuccess(withMessage: "支付成功", duration: ToastTimer) {
  82. /// 支付成功
  83. MTP2BusinessCore.shared.broadcastManager?.post(action: ActionType.PaySuccess, object: result)
  84. }
  85. }
  86. }
  87. }
  88. } else if url.host == "platformapi" {
  89. /// 支付宝钱包快登授权返回authCode
  90. AlipaySDK.defaultService().processAuthResult(url) { result in
  91. ///【由于在跳转支付宝客户端支付的过程中,商户app在后台很可能被系统kill了,所以pay接口的callback就会失效,请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
  92. dPrint("-------\(String(describing: result))")
  93. DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
  94. /// 支付失败
  95. if let rs = result,
  96. (rs as NSDictionary)["resultStatus"] as? String != "9000" {
  97. let msg = (rs as NSDictionary)["memo"] as? String
  98. WHToast.showMessage("支付失败,原因:\(msg ?? "请稍候查看单据信息")", duration: ToastTimer, finishHandler: {})
  99. } else {
  100. WHToast.showSuccess(withMessage: "支付成功", duration: ToastTimer) {
  101. /// 支付成功
  102. MTP2BusinessCore.shared.broadcastManager?.post(action: ActionType.PaySuccess, object: result)
  103. }
  104. }
  105. }
  106. }
  107. }
  108. return true
  109. }
  110. // MARK: - Core Data stack
  111. lazy var persistentContainer: NSPersistentContainer = {
  112. let container = NSPersistentContainer(name: "MTP2DataModel")
  113. container.loadPersistentStores(completionHandler: { (storeDescription, error) in
  114. if let error = error as NSError? {
  115. fatalError("Unresolved error \(error), \(error.userInfo)")
  116. }
  117. })
  118. return container
  119. }()
  120. var mainManagedObjectContext: NSManagedObjectContext {
  121. return persistentContainer.viewContext
  122. }
  123. lazy var backGroundObjectContext: NSManagedObjectContext = {
  124. let backGroundObjectContext = persistentContainer.newBackgroundContext()
  125. return backGroundObjectContext
  126. }()
  127. // MARK: - Core Data Saving support
  128. func saveContext () {
  129. let context = persistentContainer.viewContext
  130. if context.hasChanges {
  131. do {
  132. try context.save()
  133. } catch {
  134. // Replace this implementation with code to handle the error appropriately.
  135. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  136. let nserror = error as NSError
  137. fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
  138. }
  139. }
  140. }
  141. // MARK: - Bugly相关
  142. func initBugly() {
  143. let config = BuglyConfig()
  144. config.debugMode = false
  145. config.channel = "qyfgypt"
  146. config.blockMonitorEnable = true
  147. config.blockMonitorTimeout = 2
  148. config.deviceIdentifier = "com.muchinfo.qyfgypt"
  149. config.reportLogLevel = BuglyLogLevel.silent
  150. config.version = app_Version
  151. Bugly.start(withAppId: "2689387582", config: config)
  152. }
  153. // MARK: - 账号处理相关
  154. /// 系统登出的方法,一般用于异常登出
  155. /// ps: 这里说明一下,异常退出时一般token已经失效,所以调用系统退出登录的方法是没有意义的。干脆就不调用了!!!
  156. /// - Parameter message: 提示内容
  157. func logout(message: String) {
  158. DispatchQueue.main.async {
  159. /// 重置管理类
  160. MTP2BusinessCore.shared.resetCore()
  161. /// showMessage
  162. WHToast.showMessage(message, duration: ToastTimer) {
  163. /// startAnimating
  164. NVActivityIndicatorPresenter.sharedInstance.startAnimating(ActivityData(message: "正在登出...", type: .ballSpinFadeLoader, color: UIColor.loding(), backgroundColor: .clear))
  165. /// 显示登录界面
  166. DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
  167. /// stopAnimating
  168. NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
  169. /// 设置主页面
  170. UIApplication.shared.keyWindow?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
  171. }
  172. }
  173. }
  174. }
  175. }
  176. // MARK: - MTP2BusinessCoreDelegate
  177. extension AppDelegate: MTP2BusinessCoreDelegate {
  178. func onNoticeChanged() {}
  179. func onReconnectChangeState(type: PacketType, state: ReconnectChangeState) {
  180. dPrint("网络连接正在进行重连,当前的状态为:\(state)")
  181. DispatchQueue.main.async {
  182. switch state {
  183. case .BeginReconnect:
  184. WHToast.showMessage("正在开始重连...", duration: ToastTimer, finishHandler: {})
  185. case .FailAndWaitPeriod:
  186. WHToast.showMessage("网络链路重连失败,正在重新尝试连接...", duration: ToastTimer, finishHandler: {})
  187. case .Logined:
  188. WHToast.showSuccess(withMessage: type == .PacketType_50 ? "交易链路重连成功" : "行情链路重连成功" , duration: ToastTimer, finishHandler: {})
  189. case .LoginFail:
  190. self.logout(message: "连接异常,请重新登录")
  191. default: break
  192. }
  193. }
  194. }
  195. func onReceiveQutoePush(quoteGoodsInfos: [(goodsHqCode: String, exchHqCode: String)]?) {
  196. /// 发送实时行情接收广播
  197. MTP2BusinessCore.shared.broadcastManager?.post(action: .ReceiveTradeQuote, object: quoteGoodsInfos)
  198. }
  199. func onReceiveUpateQuoteCompleted(quoteGoodsInfos: [(goodsHqCode: String, exchHqCode: String)]?) {
  200. /// 盘面更新当成一次实时行情接收
  201. MTP2BusinessCore.shared.broadcastManager?.post(action: .ReceiveTradeQuote, object: quoteGoodsInfos)
  202. }
  203. func onCustOfflineNtf(code: Int, er: ErrorInfo?) {
  204. if code == 0 {
  205. self.logout(message: "登录状态失效,请重新登录")
  206. } else {
  207. self.logout(message: er?.retMsg ?? "请求超时,请重新登录" + "(\(code))")
  208. }
  209. }
  210. /// 资金变化通知
  211. func onMoneyChange() {
  212. MTP2BusinessCore.shared.broadcastManager?.post(action: .FundationInfoReloadData, object: nil)
  213. }
  214. /// 头寸发生变化
  215. func PosChangedNtf() {
  216. MTP2BusinessCore.shared.broadcastManager?.post(action: .PosChangedNtf, object: nil)
  217. }
  218. /// 预售状态变更通知
  219. func PresaleStatutsChangeNtf() {
  220. MTP2BusinessCore.shared.broadcastManager?.post(action: .PresaleStatutsChangeNtf, object: nil)
  221. }
  222. /// 风控通知
  223. func userChangeNtf() {}
  224. func dealChange() {}
  225. }
  226. extension AppDelegate {
  227. func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
  228. if self.isRotation { /// 允许横屏
  229. return .all
  230. } else {
  231. return .portrait
  232. }
  233. }
  234. }