AppDelegate.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. //
  2. // AppDelegate.swift
  3. // O2Platform
  4. //
  5. // Created by 刘振兴 on 16/6/14.
  6. // Copyright © 2016年 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import CocoaLumberjack
  10. import AlamofireNetworkActivityIndicator
  11. import UserNotifications
  12. import O2OA_Auth_SDK
  13. import Flutter
  14. import IQKeyboardManagerSwift
  15. let isProduction = true
  16. @UIApplicationMain
  17. class AppDelegate: FlutterAppDelegate, JPUSHRegisterDelegate, UNUserNotificationCenterDelegate {
  18. var _mapManager: BMKMapManager?
  19. //中心服务器节点类
  20. public static let o2Collect = O2Collect()
  21. //网络监听
  22. public let o2ReachabilityManager = O2ReachabilityManager.sharedInstance
  23. // flutter engine
  24. var flutterEngine : FlutterEngine?
  25. override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  26. if #available(iOS 13.0, *) {
  27. window.overrideUserInterfaceStyle = .light
  28. }
  29. let themeName = AppConfigSettings.shared.themeName
  30. if themeName != "" {
  31. //主题
  32. print("主题色:\(themeName)")
  33. O2ThemeManager.setTheme(plistName: themeName, path: .mainBundle)
  34. }else {
  35. O2ThemeManager.setTheme(plistName: "red", path: .mainBundle)
  36. }
  37. //搜索框
  38. UISearchBar.appearance().theme_barTintColor = ThemeColorPicker(keyPath: "Base.base_color")
  39. UISearchBar.appearance().tintColor = UIColor.white
  40. UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).theme_tintColor = ThemeColorPicker(keyPath: "Base.base_color")
  41. //启动日志管理器
  42. O2Logger.startLogManager()
  43. //日志文件
  44. _ = O2Logger.getLogFiles()
  45. O2Logger.debug("设置运行版本==========,\(PROJECTMODE)")
  46. //网络检查
  47. o2ReachabilityManager.startListening()
  48. //Alamofire
  49. NetworkActivityIndicatorManager.shared.isEnabled = true
  50. //db
  51. let _ = DBManager.shared
  52. //设置一个是否第一授权的标志
  53. if #available(iOS 10.0, *){
  54. let center = UNUserNotificationCenter.current()
  55. center.delegate = self
  56. let options:UNAuthorizationOptions = [.badge,.alert,.sound]
  57. center.requestAuthorization(options: options, completionHandler: { (granted, err) in
  58. if granted == true {
  59. //记录已经打开授权
  60. //print("aaaaaaaaaaaa")
  61. AppConfigSettings.shared.notificationGranted = true
  62. AppConfigSettings.shared.firstGranted = true
  63. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  64. }else{
  65. //记录禁用授权
  66. AppConfigSettings.shared.notificationGranted = false
  67. AppConfigSettings.shared.firstGranted = true
  68. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  69. }
  70. })
  71. }else{
  72. let types:UIUserNotificationType = [.badge,.alert,.sound]
  73. let setting = UIUserNotificationSettings(types: types, categories: nil)
  74. UIApplication.shared.registerUserNotificationSettings(setting)
  75. }
  76. //Buglyy异常上报
  77. Bugly.start(withAppId: BUGLY_ID)
  78. //JPush
  79. _setupJPUSH()
  80. JPUSHService.setup(withOption: launchOptions, appKey: JPUSH_APP_KEY, channel: JPUSH_channel, apsForProduction: isProduction)
  81. //JMessage
  82. JMessage.setupJMessage(launchOptions, appKey: JPUSH_APP_KEY, channel: JPUSH_channel, apsForProduction: isProduction, category: nil, messageRoaming: true)
  83. _setupJMessage()
  84. _mapManager = BMKMapManager()
  85. BMKMapManager.setCoordinateTypeUsedInBaiduMapSDK(BMK_COORDTYPE_BD09LL)
  86. _mapManager?.start(BAIDU_MAP_KEY, generalDelegate: nil)
  87. JPUSHService.registrationIDCompletionHandler { (resCode, registrationID) in
  88. if resCode == 0 {
  89. O2Logger.debug("registrationID获取成功\(registrationID ?? "")")
  90. O2AuthSDK.shared.setDeviceToken(token: registrationID ?? "registrationIDerror0x0x")
  91. }else{
  92. O2Logger.debug("registrationID获取失败,code:\(resCode)")
  93. O2AuthSDK.shared.setDeviceToken(token: registrationID ?? "registrationIDerror0x0x")
  94. }
  95. }
  96. // OOPlusButtonSubclass.register()
  97. OOTabBarHelper.initTabBarStyle()
  98. //
  99. IQKeyboardManager.shared.enable = true
  100. return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  101. }
  102. // MARK:- private func Jpush
  103. private func _setupJPUSH() {
  104. let entity = JPUSHRegisterEntity()
  105. entity.types = NSInteger(UNAuthorizationOptions.alert.rawValue) |
  106. NSInteger(UNAuthorizationOptions.sound.rawValue) |
  107. NSInteger(UNAuthorizationOptions.badge.rawValue)
  108. JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
  109. }
  110. // MARK: - private func
  111. private func _setupJMessage() {
  112. // JMessage.setDebugMode()
  113. JMessage.add(self, with: nil)
  114. JMessage.register(forRemoteNotificationTypes:
  115. UNAuthorizationOptions.badge.rawValue |
  116. UNAuthorizationOptions.sound.rawValue |
  117. UNAuthorizationOptions.alert.rawValue,
  118. categories: nil)
  119. }
  120. //注册 APNs 获得device token
  121. override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  122. super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
  123. DDLogDebug("get the deviceToken \(deviceToken)")
  124. NotificationCenter.default.post(name: Notification.Name(rawValue: "DidRegisterRemoteNotification"), object: deviceToken)
  125. JPUSHService.registerDeviceToken(deviceToken)
  126. JMessage.registerDeviceToken(deviceToken)
  127. }
  128. override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  129. DDLogDebug("open url :\(url.absoluteString)")
  130. return true
  131. }
  132. override func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
  133. if notificationSettings.types.rawValue == 0 {
  134. AppConfigSettings.shared.notificationGranted = false
  135. AppConfigSettings.shared.firstGranted = true
  136. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  137. }else{
  138. AppConfigSettings.shared.notificationGranted = true
  139. AppConfigSettings.shared.firstGranted = true
  140. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  141. }
  142. }
  143. //实现注册 APNs 失败接口
  144. override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  145. DDLogError("didFailToRegisterForRemoteNotificationsWithError: \(error.localizedDescription)")
  146. }
  147. override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  148. JPUSHService.handleRemoteNotification(userInfo)
  149. DDLogDebug("收到通知,\(userInfo)")
  150. NotificationCenter.default.post(name: Notification.Name(rawValue: "AddNotificationCount"), object: nil)
  151. }
  152. override func applicationWillEnterForeground(_ application: UIApplication) {
  153. application.applicationIconBadgeNumber = 0
  154. application.cancelAllLocalNotifications()
  155. }
  156. override func applicationDidBecomeActive(_ application: UIApplication) {
  157. }
  158. override func applicationDidEnterBackground(_ application: UIApplication) {
  159. application.applicationIconBadgeNumber = 0
  160. application.cancelAllLocalNotifications()
  161. }
  162. deinit {
  163. o2ReachabilityManager.stopListening()
  164. }
  165. // iOS 12 Support
  166. @available(iOS 12.0, *)
  167. func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification!) {
  168. // open
  169. if (notification != nil && (notification?.request.trigger?.isKind(of: UNPushNotificationTrigger.self) == true) ) {
  170. //从通知界面直接进入应用
  171. DDLogInfo("从通知界面直接进入应用............")
  172. }else{
  173. //从通知设置界面进入应用
  174. DDLogInfo("从通知设置界面进入应用............")
  175. }
  176. }
  177. @available(iOS 10.0, *)
  178. func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!,
  179. withCompletionHandler completionHandler: ((Int) -> Void)!) {
  180. let userInfo = notification.request.content.userInfo
  181. let request = notification.request // 收到推送的请求
  182. let content = request.content // 收到推送的消息内容
  183. let badge = content.badge // 推送消息的角标
  184. let body = content.body // 推送消息体
  185. let sound = content.sound // 推送消息的声音
  186. let subtitle = content.subtitle // 推送消息的副标题
  187. let title = content.title // 推送消息的标题
  188. if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
  189. JPUSHService.handleRemoteNotification(userInfo)
  190. }else{
  191. //判断为本地通知
  192. O2Logger.debug("iOS10 前台收到本地通知:{\nbody:\(body),\ntitle:\(title),\nsubtitle:\(subtitle),\nbadge:\(badge ?? 0),\nsound:\(sound.debugDescription)")
  193. }
  194. UIApplication.shared.applicationIconBadgeNumber = 0
  195. JPUSHService.setBadge(0)
  196. completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue|UNNotificationPresentationOptions.badge.rawValue|UNNotificationPresentationOptions.sound.rawValue))
  197. }
  198. @available(iOS 10.0, *)
  199. func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
  200. let userInfo = response.notification.request.content.userInfo
  201. let request = response.notification.request // 收到推送的请求
  202. let content = request.content // 收到推送的消息内容
  203. let badge = content.badge // 推送消息的角标
  204. let body = content.body // 推送消息体
  205. let sound = content.sound // 推送消息的声音
  206. let subtitle = content.subtitle // 推送消息的副标题
  207. let title = content.title // 推送消息的标题
  208. if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
  209. JPUSHService.handleRemoteNotification(userInfo)
  210. }else{
  211. //判断为本地通知
  212. O2Logger.debug("iOS10 前台收到本地通知:{\nbody:\(body),\ntitle:\(title),\nsubtitle:\(subtitle),\nbadge:\(badge ?? 0),\nsound:\(sound.debugDescription)")
  213. }
  214. UIApplication.shared.applicationIconBadgeNumber = 0
  215. JPUSHService.setBadge(0)
  216. completionHandler()
  217. }
  218. }
  219. //MARK: - JMessage Delegate
  220. extension AppDelegate: JMessageDelegate {
  221. func onDBMigrateStart() {
  222. }
  223. func onDBMigrateFinishedWithError(_ error: Error!) {
  224. // self.showSuccess(title: "数据库升级完成")
  225. }
  226. func onReceive(_ event: JMSGUserLoginStatusChangeEvent!) {
  227. switch event.eventType.rawValue {
  228. // case JMSGLoginStatusChangeEventType.eventNotificationLoginKicked.rawValue:
  229. // DDLogInfo("被踢 重新登录")
  230. // _reLogin()
  231. // break
  232. case JMSGLoginStatusChangeEventType.eventNotificationLoginKicked.rawValue,
  233. JMSGLoginStatusChangeEventType.eventNotificationServerAlterPassword.rawValue,
  234. JMSGLoginStatusChangeEventType.eventNotificationUserLoginStatusUnexpected.rawValue:
  235. DDLogInfo("被踢 重新登录")
  236. _reLogin()
  237. default:
  238. break
  239. }
  240. }
  241. func onReceive(_ event: JMSGFriendNotificationEvent!) {
  242. switch event.eventType.rawValue {
  243. case JMSGFriendEventType.eventNotificationReceiveFriendInvitation.rawValue,
  244. JMSGFriendEventType.eventNotificationAcceptedFriendInvitation.rawValue,
  245. JMSGFriendEventType.eventNotificationDeclinedFriendInvitation.rawValue:
  246. cacheInvitation(event: event)
  247. case JMSGFriendEventType.eventNotificationDeletedFriend.rawValue,
  248. JMSGFriendEventType.eventNotificationReceiveServerFriendUpdate.rawValue:
  249. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
  250. default:
  251. break
  252. }
  253. }
  254. private func cacheInvitation(event: JMSGNotificationEvent) {
  255. let friendEvent = event as! JMSGFriendNotificationEvent
  256. let user = friendEvent.getFromUser()
  257. let reason = friendEvent.getReason()
  258. let info = JCVerificationInfo.create(username: user!.username, nickname: user?.nickname, appkey: user!.appKey!, resaon: reason, state: JCVerificationType.wait.rawValue)
  259. switch event.eventType.rawValue {
  260. case JMSGFriendEventType.eventNotificationReceiveFriendInvitation.rawValue:
  261. info.state = JCVerificationType.receive.rawValue
  262. JCVerificationInfoDB.shareInstance.insertData(info)
  263. case JMSGFriendEventType.eventNotificationAcceptedFriendInvitation.rawValue:
  264. info.state = JCVerificationType.accept.rawValue
  265. JCVerificationInfoDB.shareInstance.updateData(info)
  266. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
  267. case JMSGFriendEventType.eventNotificationDeclinedFriendInvitation.rawValue:
  268. info.state = JCVerificationType.reject.rawValue
  269. JCVerificationInfoDB.shareInstance.updateData(info)
  270. default:
  271. break
  272. }
  273. if UserDefaults.standard.object(forKey: kUnreadInvitationCount) != nil {
  274. let count = UserDefaults.standard.object(forKey: kUnreadInvitationCount) as! Int
  275. UserDefaults.standard.set(count + 1, forKey: kUnreadInvitationCount)
  276. } else {
  277. UserDefaults.standard.set(1, forKey: kUnreadInvitationCount)
  278. }
  279. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
  280. }
  281. func _logout() {
  282. JMSGUser.logout(nil)
  283. JCVerificationInfoDB.shareInstance.queue = nil
  284. UserDefaults.standard.removeObject(forKey: kCurrentUserName)
  285. }
  286. func _reLogin() {
  287. if let account = O2AuthSDK.shared.myInfo() {
  288. JMSGUser.login(withUsername: account.id!, password: "QazWsxEdc!@#", completionHandler: { (resultObject, errMsg) in
  289. if errMsg == nil {
  290. DDLogInfo("IM登录成功,user = \(String(describing: resultObject))")
  291. }else{
  292. DDLogError("IM登录失改,error = \(String(describing: errMsg))")
  293. }
  294. })
  295. }else {
  296. DDLogError("_reLogin 。。。。。 IM登录失败,error = 当前登录用户为空!!!")
  297. }
  298. }
  299. }