| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268 |
- //
- // AppDelegate.swift
- // rrr
- //
- // Created by Muchinfo on 2020/12/28.
- //
- import UIKit
- import CoreData
- import IQKeyboardManagerSwift
- import HandyJSON
- import Bugly
- import WHToast
- import NVActivityIndicatorView
- @UIApplicationMain
- class AppDelegate: UIResponder, UIApplicationDelegate {
-
- // MARK: - 属性列表
- /// 是否允许横屏
- var isRotation: Bool = false
- /// window
- var window: UIWindow?
-
- func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
- // Override point for customization after application launch.
-
- /// 配置底层单例实例化
- let businessCore = MTP2BusinessCore.shared
- businessCore.delegate = self
- /// 初始化数据库
- DatabaseHelper.firstOpenInitialData()
- ///第三方收起键盘
- IQKeyboardManager.shared.enable = true
- IQKeyboardManager.shared.enableAutoToolbar = true
- IQKeyboardManager.shared.shouldResignOnTouchOutside = true
- /// 全局配置字段解析忽略大小写
- HandyJSONConfiguration.deserializeOptions = .caseInsensitive
- /// Bugly配置
- initBugly()
-
- /// 判断其是否第一次启动
- if UserDefaultsUtils.isFirstOpen() {
- /// 系统设置字体大小
- UserDefaultsUtils.setFontSize(1.0)
- /// 默认登录时间有效期
- UserDefaultsUtils.setPwdDown(8)
- }
- /// 修改第一次运行状态标志
- UserDefaultsUtils.setOpened()
-
- return true
- }
-
- 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, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
-
- }
-
- func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
- if url.host == "safepay" {
- /// 跳转支付宝钱包进行支付,处理支付结果
- AlipaySDK.defaultService().processOrder(withPaymentResult: url) { result in
- dPrint("-------\(String(describing: result))")
- DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
- /// 支付失败
- if let rs = result,
- (rs as NSDictionary)["resultStatus"] as? String != "9000" {
- let msg = (rs as NSDictionary)["memo"] as? String
- WHToast.showMessage("支付失败,原因:\(msg ?? "请稍候查看单据信息")", duration: ToastTimer, finishHandler: {})
- } else {
- WHToast.showSuccess(withMessage: "支付成功", duration: ToastTimer) {
- /// 支付成功
- MTP2BusinessCore.shared.broadcastManager?.post(action: ActionType.PaySuccess, object: result)
- }
- }
- }
- }
- } else if url.host == "platformapi" {
- /// 支付宝钱包快登授权返回authCode
- AlipaySDK.defaultService().processAuthResult(url) { result in
- ///【由于在跳转支付宝客户端支付的过程中,商户app在后台很可能被系统kill了,所以pay接口的callback就会失效,请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
- dPrint("-------\(String(describing: result))")
- DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
- /// 支付失败
- if let rs = result,
- (rs as NSDictionary)["resultStatus"] as? String != "9000" {
- let msg = (rs as NSDictionary)["memo"] as? String
- WHToast.showMessage("支付失败,原因:\(msg ?? "请稍候查看单据信息")", duration: ToastTimer, finishHandler: {})
- } else {
- WHToast.showSuccess(withMessage: "支付成功", duration: ToastTimer) {
- /// 支付成功
- MTP2BusinessCore.shared.broadcastManager?.post(action: ActionType.PaySuccess, object: result)
- }
- }
- }
- }
- }
- return true
- }
- // 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 {
- // Replace this implementation with code to handle the error appropriately.
- // 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.
- let nserror = error as NSError
- fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
- }
- }
- }
- // MARK: - Bugly相关
- func initBugly() {
- let config = BuglyConfig()
- config.debugMode = false
- config.channel = "qyfgypt"
- config.blockMonitorEnable = true
- config.blockMonitorTimeout = 2
- config.deviceIdentifier = "com.muchinfo.qyfgypt"
- config.reportLogLevel = BuglyLogLevel.silent
- config.version = app_Version
- Bugly.start(withAppId: "2689387582", config: config)
- }
-
- // MARK: - 账号处理相关
- /// 系统登出的方法,一般用于异常登出
- /// ps: 这里说明一下,异常退出时一般token已经失效,所以调用系统退出登录的方法是没有意义的。干脆就不调用了!!!
- /// - Parameter message: 提示内容
- func logout(message: String) {
- DispatchQueue.main.async {
- /// 重置管理类
- MTP2BusinessCore.shared.resetCore()
- /// showMessage
- WHToast.showMessage(message, duration: ToastTimer) {
- /// startAnimating
- NVActivityIndicatorPresenter.sharedInstance.startAnimating(ActivityData(message: "正在登出...", type: .ballSpinFadeLoader, color: UIColor.loding(), backgroundColor: .clear))
- /// 显示登录界面
- DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
- /// stopAnimating
- NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
- /// 设置主页面
- UIApplication.shared.keyWindow?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
- }
- }
- }
- }
- }
- // MARK: - MTP2BusinessCoreDelegate
- extension AppDelegate: MTP2BusinessCoreDelegate {
-
- func onNoticeChanged() {}
-
- func onReconnectChangeState(type: PacketType, state: ReconnectChangeState) {
- dPrint("网络连接正在进行重连,当前的状态为:\(state)")
- DispatchQueue.main.async {
- switch state {
- case .BeginReconnect:
- WHToast.showMessage("正在开始重连...", duration: ToastTimer, finishHandler: {})
- case .FailAndWaitPeriod:
- WHToast.showMessage("网络链路重连失败,正在重新尝试连接...", duration: ToastTimer, finishHandler: {})
- case .Logined:
- WHToast.showSuccess(withMessage: type == .PacketType_50 ? "交易链路重连成功" : "行情链路重连成功" , duration: ToastTimer, 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, er: ErrorInfo?) {
- if code == 0 {
- self.logout(message: "登录状态失效,请重新登录")
- } else {
- self.logout(message: er?.retMsg ?? "请求超时,请重新登录" + "(\(code))")
- }
- }
-
- /// 资金变化通知
- func onMoneyChange() {
- MTP2BusinessCore.shared.broadcastManager?.post(action: .FundationInfoReloadData, object: nil)
- }
-
- /// 头寸发生变化
- func PosChangedNtf() {
- MTP2BusinessCore.shared.broadcastManager?.post(action: .PosChangedNtf, object: nil)
- }
-
- /// 预售状态变更通知
- func PresaleStatutsChangeNtf() {
- MTP2BusinessCore.shared.broadcastManager?.post(action: .PresaleStatutsChangeNtf, object: nil)
- }
-
- /// 风控通知
- func userChangeNtf() {}
- func dealChange() {}
- }
- extension AppDelegate {
- func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
- if self.isRotation { /// 允许横屏
- return .all
- } else {
- return .portrait
- }
- }
- }
|