| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309 |
- //
- // AppDelegate.swift
- // MTP2_iOS
- //
- // Created by zhongyuan on 2018/3/13.
- // Copyright © 2018年 zhongyuan.All rights reserved.
- //
- import UIKit
- import CoreData
- import NVActivityIndicatorView
- import IQKeyboardManagerSwift
- import HandyJSON
- import Bugly
- import WHToast
- @UIApplicationMain
- class AppDelegate: UIResponder, UIApplicationDelegate {
-
- var weixin_uuid = "wxc22f6c8a0abb5301"
- /// 当前选择三方登录目标。值0为实盘,1为模拟盘
- var currentAuthType = 0
-
- var window: UIWindow?
- lazy var customStatusBar = NotificationTopBarWindow()
-
- /// 是否允许横屏
- var isRotation: Bool = false
-
- func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
-
- /// 配置底层单例实例化
- let businessCore = MTP2BusinessCore.shared
- businessCore.delegate = self
-
- ///第三方收起键盘
- IQKeyboardManager.shared.enable = true
- /// 初始化数据库
- DatabaseHelper.firstOpenInitialData()
- /// 全局配置字段解析忽略大小写
- HandyJSONConfiguration.deserializeOptions = .caseInsensitive
-
- /// 注册微信支付
- UMSPPPayUnifyPayPlugin.registerApp(weixin_uuid, universalLink: "https://mobl-test.chinaums.com/")
-
- window = UIWindow()
- window?.backgroundColor = UIColorFromHex(rgbValue: 0xffffff)
-
- /// Bugly配置
- initBugly()
- /// 修改第一次运行状态标志
- UserDefaultsUtils.setOpened()
- /// 主页配置
- mainPageConfiguration()
-
- NotificationCenter.default.addObserver(forName: NSNotification.Name.NSManagedObjectContextDidSave, object: self.backGroundObjectContext, queue: OperationQueue.main) { [weak self](noti) in
- self?.mainManagedObjectContext.mergeChanges(fromContextDidSave: noti)
- }
-
- window?.makeKeyAndVisible()
- return true
- }
-
- deinit {
- NotificationCenter.default.removeObserver(self)
- }
-
- func applicationWillResignActive(_ application: UIApplication) {
- // 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.
- // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
- }
-
- func applicationDidEnterBackground(_ application: UIApplication) {
- // 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.
- // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
- // application
- saveContext()
- }
-
- func applicationWillEnterForeground(_ application: UIApplication) {
- // 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.
- }
-
- func applicationDidBecomeActive(_ application: UIApplication) {
- // 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.
- }
-
- func applicationWillTerminate(_ application: UIApplication) {
- // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
- saveContext()
- }
-
- func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
- if #available(iOS 8.0, *) {
- /// 当用户首次使用新版本发起支付时,会出现安全验证,安全验证的处理如下
- return UMSPPPayUnifyPayPlugin.handleOpenUniversalLink(userActivity, otherDelegate: WeiChatOtherManager.share())
- } else {
- return true
- }
- }
-
- func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
- /// 支付成功后回调商户App 当在微信小程序中完成支付或者取消支付后,点击返回商户,微信会向我们的app发送消息,sdk解析消息,通过UMSPPayUnifyPayPlugin 中的block回调支付结果
- let string = url.absoluteString
- if string.hasPrefix("haishangbaoyealipay://") { /// 支付宝支付
- UMSPPPayUnifyPayPlugin.aliMiniPayHandleOpen(url)
- return true
- } else if string.hasPrefix("haishangbaoyeunifypay://") { /// 云闪付支付
- UMSPPPayUnifyPayPlugin.cloudPayHandleOpen(url)
- return true
- }
- /// 微信支付
- return UMSPPPayUnifyPayPlugin.handleOpen(url, otherDelegate: WeiChatOtherManager.share())
- }
-
- // MARK: - 系统横屏支持
- var blockRotation = Bool()
- // MARK: - 账号处理相关
- /// 系统登出的方法,一般用于异常登出
- /// ps: 这里说明一下,异常退出时一般token已经失效,所以调用系统退出登录的方法是没有意义的。干脆就不调用了!!!
- /// - Parameter message: 提示内容
- func logout(message: String) {
- /// 重置管理类
- MTP2BusinessCore.shared.resetCore()
-
- if self.customStatusBar.isShowing {
- self.customStatusBar.dismiss()
- }
-
- window?.rootViewController?.presentedViewControllerVisibleInWindow.showHintController(title: "提示", message: message) { _ in
- /// 开启Loading
- NVActivityIndicatorPresenter.sharedInstance.startAnimating(ActivityData(message: "正在登出...", type: .ballClipRotate, color: UIColorFromHex(rgbValue: 0xA8B6CC)), NVActivityIndicatorView.DEFAULT_FADE_IN_ANIMATION)
-
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2.0) {
- NVActivityIndicatorPresenter.sharedInstance.stopAnimating(NVActivityIndicatorView.DEFAULT_FADE_OUT_ANIMATION)
- /// 显示登录界面
- self.window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
- }
- }
- }
-
- // MARK: - Bugly相关
- func initBugly() {
- let config = BuglyConfig()
- config.debugMode = false
- config.channel = "Fir"
- config.blockMonitorEnable = true
- config.blockMonitorTimeout = 2
- config.deviceIdentifier = "com.mtp.llqh"
- config.reportLogLevel = BuglyLogLevel.silent
- config.version = app_Version
- Bugly.start(withAppId: "eb6c7e9d71", config: config)
- }
-
- // MARK: - Core Data stack
-
- lazy var persistentContainer: NSPersistentContainer = {
- let container = NSPersistentContainer(name: "MTP2DataModel")
- container.loadPersistentStores(completionHandler: { (storeDescription, error) in
- if let error = error as NSError? {
- fatalError("Unresolved error \(error), \(error.userInfo)")
- }
- })
- return container
- }()
-
- var mainManagedObjectContext: NSManagedObjectContext {
- return persistentContainer.viewContext
- }
-
- lazy var backGroundObjectContext: NSManagedObjectContext = {
- let backGroundObjectContext = persistentContainer.newBackgroundContext()
- return backGroundObjectContext
- }()
-
- // MARK: - Core Data Saving support
-
- func saveContext () {
- let context = persistentContainer.viewContext
- if context.hasChanges {
- do {
- try context.save()
- } catch {
- let nserror = error as NSError
- fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
- }
- }
- }
-
- // MARK: - 三方登录
- /// 解密相关数据的方法
- ///
- /// - Parameter value: 密文
- /// - Returns: 明文
- func getString(value: String) -> String? {
- /// Base64解码
- guard let encodedData = Data(base64Encoded: value, options: Data.Base64DecodingOptions.init(rawValue: 0)) else {
- return nil
- }
-
- /// 解密
- if let decryptData = MTP2Crypto.decrypt(ciphertext: encodedData.subdata(in: 4 ..< encodedData.count - 8), key: MTP2BusinessCore.aes_des_key) {
- return String(data: decryptData, encoding: String.Encoding.utf8)
- } else {
- return nil
- }
- }
- }
- // MARK: - MTP2BusinessCoreDelegate
- extension AppDelegate: MTP2BusinessCoreDelegate {
- func onReconnectChangeState(type: PacketType, state: ReconnectChangeState) {
- // dPrint("网络连接正在进行重连,当前的状态为:\(state)")
- // DispatchQueue.main.async {
- // switch state {
- // case .BeginReconnect:
- // let message = "正在开始重连......".localized
- // if (self.window?.rootViewController as? UITabBarController) != nil {
- // WHToast.showError(withMessage: message, duration: 1.5, finishHandler: {})
- // }
- // case .FailAndWaitPeriod:
- // let message = "网络已断开......".localized
- // if (self.window?.rootViewController as? UITabBarController) != nil {
- // WHToast.showError(withMessage: message, duration: 1.5, finishHandler: {})
- // }
- // case .Logined:
- // let message = "网络重连成功".localized
- // if (self.window?.rootViewController as? UITabBarController) != nil {
- // WHToast.showSuccess(withMessage: message, duration: 1.5, finishHandler: {})
- // }
- // case .LoginFail:
- // self.logout(message: "连接异常,请重新登录")
- // default:
- // break
- // }
- // }
- }
-
- func onReceiveQutoePush(quoteGoodsInfos: [(goodsHqCode: String, exchHqCode: String)]?) {
- /// 发送实时行情接收广播
- MTP2BusinessCore.shared.broadcastManager?.post(action: .ReceiveTradeQuote, object: quoteGoodsInfos)
- }
-
- func onReceiveUpateQuoteCompleted(quoteGoodsInfos: [(goodsHqCode: String, exchHqCode: String)]?) {
- /// 盘面更新当成一次实时行情接收
- MTP2BusinessCore.shared.broadcastManager?.post(action: .ReceiveTradeQuote, object: quoteGoodsInfos)
- }
-
- func onCustOfflineNtf(code: Int, error: ErrorInfo?) {
- dPrint("[\(#function)] 交易账户被动离线")
-
- DispatchQueue.main.async {
- if code == 0 {
- self.logout(message: "登录状态失效,请重新登录".localized)
- } else {
- self.logout(message: error?.retMsg ?? "请求超时,请重新登录".localized + "(\(code))")
- }
- }
- }
-
- func onMoneyChange() {
- MTP2BusinessCore.shared.broadcastManager?.post(action: .FundationInfoReloadData, object: nil)
- }
-
- func dealChange() {
- /// 刷新交易界面数据
- MTP2BusinessCore.shared.broadcastManager?.post(action: .DealChange, object: nil)
- }
-
- /// 头寸发生变化
- func PosChangedNtf() {
- /// 头寸发生变化
- MTP2BusinessCore.shared.broadcastManager?.post(action: .PosChangedNtf, object: nil)
- }
-
- /// 风控通知
- func userChangeNtf() {
- /// 通知变化
- MTP2BusinessCore.shared.broadcastManager?.post(action: .NoticeChange, object: self)
- DispatchQueue.main.async {
- if (self.window?.rootViewController as? UITabBarController) != nil {
- self.customStatusBar.addMessage("斩仓通知".localized, delay: 2)
- }
- }
- }
-
- /// 公告变更通知
- func onNoticeChanged() {}
- }
- extension AppDelegate {
- func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
- if self.isRotation { /// 允许横屏
- return .all
- } else {
- return .portrait
- }
- }
-
- /// 主页相关
- func mainPageConfiguration() {
- window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
- }
- }
|