AppDelegate.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 static var deviceData = CollectDeviceData()
  23. //网络监听
  24. public let o2ReachabilityManager = O2ReachabilityManager.sharedInstance
  25. // flutter engine
  26. var flutterEngine : FlutterEngine?
  27. override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  28. let themeName = AppConfigSettings.shared.themeName
  29. if themeName != "" {
  30. //主题
  31. print("主题色:\(themeName)")
  32. O2ThemeManager.setTheme(plistName: themeName, path: .mainBundle)
  33. }else {
  34. O2ThemeManager.setTheme(plistName: "red", path: .mainBundle)
  35. }
  36. //搜索框
  37. UISearchBar.appearance().theme_barTintColor = ThemeColorPicker(keyPath: "Base.base_color")
  38. UISearchBar.appearance().tintColor = UIColor.white
  39. UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).theme_tintColor = ThemeColorPicker(keyPath: "Base.base_color")
  40. //启动日志管理器
  41. O2Logger.startLogManager()
  42. //日志文件
  43. _ = O2Logger.getLogFiles()
  44. O2Logger.debug("设置运行版本==========,\(PROJECTMODE)")
  45. //网络检查
  46. o2ReachabilityManager.startListening()
  47. //Alamofire
  48. NetworkActivityIndicatorManager.shared.isEnabled = true
  49. //设置一个是否第一授权的标志
  50. if #available(iOS 10.0, *){
  51. let center = UNUserNotificationCenter.current()
  52. center.delegate = self
  53. let options:UNAuthorizationOptions = [.badge,.alert,.sound]
  54. center.requestAuthorization(options: options, completionHandler: { (granted, err) in
  55. if granted == true {
  56. //记录已经打开授权
  57. //print("aaaaaaaaaaaa")
  58. AppConfigSettings.shared.notificationGranted = true
  59. AppConfigSettings.shared.firstGranted = true
  60. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  61. }else{
  62. //记录禁用授权
  63. AppConfigSettings.shared.notificationGranted = false
  64. AppConfigSettings.shared.firstGranted = true
  65. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  66. }
  67. })
  68. }else{
  69. let types:UIUserNotificationType = [.badge,.alert,.sound]
  70. let setting = UIUserNotificationSettings(types: types, categories: nil)
  71. UIApplication.shared.registerUserNotificationSettings(setting)
  72. }
  73. //UMessage.setLogEnabled(true)
  74. //蒲公英
  75. let pgyAppId = PGY_APP_ID
  76. PgyManager.shared().themeColor = base_color
  77. PgyManager.shared().feedbackActiveType = KPGYFeedbackActiveType.pgyFeedbackActiveTypeThreeFingersPan
  78. PgyManager.shared().start(withAppId: pgyAppId)
  79. PgyUpdateManager.sharedPgy().start(withAppId: pgyAppId)
  80. if UIDevice.deviceModelReadable() == "Simulator" {
  81. AppDelegate.deviceData.name = UIDevice.idForVendor()!
  82. }
  83. //Buglyy异常上报
  84. Bugly.start(withAppId: BUGLY_ID)
  85. //JPush
  86. _setupJPUSH()
  87. JPUSHService.setup(withOption: launchOptions, appKey: JPUSH_APP_KEY, channel: JPUSH_channel, apsForProduction: isProduction)
  88. //JMessage
  89. JMessage.setupJMessage(launchOptions, appKey: JPUSH_APP_KEY, channel: JPUSH_channel, apsForProduction: isProduction, category: nil, messageRoaming: true)
  90. _setupJMessage()
  91. _mapManager = BMKMapManager()
  92. BMKMapManager.setCoordinateTypeUsedInBaiduMapSDK(BMK_COORDTYPE_BD09LL)
  93. _mapManager?.start(BAIDU_MAP_KEY, generalDelegate: nil)
  94. JPUSHService.registrationIDCompletionHandler { (resCode, registrationID) in
  95. if resCode == 0 {
  96. O2Logger.debug("registrationID获取成功\(registrationID ?? "")")
  97. //AppDelegate.deviceData.name = registrationID
  98. O2AuthSDK.shared.setDeviceToken(token: registrationID ?? "registrationIDerror0x0x")
  99. }else{
  100. O2Logger.debug("registrationID获取失败,code:\(resCode)")
  101. O2AuthSDK.shared.setDeviceToken(token: registrationID ?? "registrationIDerror0x0x")
  102. }
  103. }
  104. // OOPlusButtonSubclass.register()
  105. OOTabBarHelper.initTabBarStyle()
  106. //
  107. IQKeyboardManager.shared.enable = true
  108. return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  109. }
  110. // MARK:- private func Jpush
  111. private func _setupJPUSH() {
  112. let entity = JPUSHRegisterEntity()
  113. entity.types = NSInteger(UNAuthorizationOptions.alert.rawValue) |
  114. NSInteger(UNAuthorizationOptions.sound.rawValue) |
  115. NSInteger(UNAuthorizationOptions.badge.rawValue)
  116. JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
  117. }
  118. // MARK: - private func
  119. private func _setupJMessage() {
  120. JMessage.setDebugMode()
  121. JMessage.add(self, with: nil)
  122. JMessage.register(forRemoteNotificationTypes:
  123. UNAuthorizationOptions.badge.rawValue |
  124. UNAuthorizationOptions.sound.rawValue |
  125. UNAuthorizationOptions.alert.rawValue,
  126. categories: nil)
  127. }
  128. //注册 APNs 获得device token
  129. override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  130. super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
  131. DDLogDebug("get the deviceToken \(deviceToken)")
  132. NotificationCenter.default.post(name: Notification.Name(rawValue: "DidRegisterRemoteNotification"), object: deviceToken)
  133. JPUSHService.registerDeviceToken(deviceToken)
  134. JMessage.registerDeviceToken(deviceToken)
  135. }
  136. override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  137. DDLogDebug("open url :\(url.absoluteString)")
  138. return true
  139. }
  140. override func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
  141. if notificationSettings.types.rawValue == 0 {
  142. AppConfigSettings.shared.notificationGranted = false
  143. AppConfigSettings.shared.firstGranted = true
  144. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  145. }else{
  146. AppConfigSettings.shared.notificationGranted = true
  147. AppConfigSettings.shared.firstGranted = true
  148. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  149. }
  150. }
  151. //实现注册 APNs 失败接口
  152. override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  153. DDLogError(error.localizedDescription)
  154. AppDelegate.deviceData.name = "104C9F7F-7403-4B3E-B6A2-C222C82074FF"
  155. }
  156. override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  157. JPUSHService.handleRemoteNotification(userInfo)
  158. O2Logger.debug("收到通知,\(userInfo)")
  159. NotificationCenter.default.post(name: Notification.Name(rawValue: "AddNotificationCount"), object: nil) //把 要addnotificationcount
  160. }
  161. //
  162. // override func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
  163. // JPUSHService.showLocalNotification(atFront: notification, identifierKey: nil)
  164. // }
  165. override func applicationWillEnterForeground(_ application: UIApplication) {
  166. application.applicationIconBadgeNumber = 0
  167. application.cancelAllLocalNotifications()
  168. }
  169. override func applicationDidBecomeActive(_ application: UIApplication) {
  170. if UIDevice.deviceModelReadable() != "Simulator" {
  171. PgyUpdateManager.sharedPgy().checkUpdate(withDelegete: self, selector: #selector(updateVersion(_:)))
  172. }
  173. }
  174. override func applicationDidEnterBackground(_ application: UIApplication) {
  175. application.applicationIconBadgeNumber = 0
  176. application.cancelAllLocalNotifications()
  177. }
  178. deinit {
  179. o2ReachabilityManager.stopListening()
  180. }
  181. // iOS 12 Support
  182. @available(iOS 12.0, *)
  183. func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification!) {
  184. // open
  185. if (notification != nil && (notification?.request.trigger?.isKind(of: UNPushNotificationTrigger.self) == true) ) {
  186. //从通知界面直接进入应用
  187. DDLogInfo("从通知界面直接进入应用............")
  188. }else{
  189. //从通知设置界面进入应用
  190. DDLogInfo("从通知设置界面进入应用............")
  191. }
  192. }
  193. //
  194. // @available(iOS 12.0, *)
  195. // func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
  196. // if (notification != nil && (notification?.request.trigger?.isKind(of: UNPushNotificationTrigger.self) == true) ) {
  197. // //从通知界面直接进入应用
  198. // DDLogInfo("从通知界面直接进入应用............")
  199. // }else{
  200. // //从通知设置界面进入应用
  201. // DDLogInfo("从通知设置界面进入应用............")
  202. // }
  203. // }
  204. @available(iOS 10.0, *)
  205. func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!,
  206. withCompletionHandler completionHandler: ((Int) -> Void)!) {
  207. let userInfo = notification.request.content.userInfo
  208. let request = notification.request // 收到推送的请求
  209. let content = request.content // 收到推送的消息内容
  210. let badge = content.badge // 推送消息的角标
  211. let body = content.body // 推送消息体
  212. let sound = content.sound // 推送消息的声音
  213. let subtitle = content.subtitle // 推送消息的副标题
  214. let title = content.title // 推送消息的标题
  215. if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
  216. JPUSHService.handleRemoteNotification(userInfo)
  217. }else{
  218. //判断为本地通知
  219. O2Logger.debug("iOS10 前台收到本地通知:{\nbody:\(body),\ntitle:\(title),\nsubtitle:\(subtitle),\nbadge:\(badge ?? 0),\nsound:\(sound.debugDescription)")
  220. }
  221. UIApplication.shared.applicationIconBadgeNumber = 0
  222. JPUSHService.setBadge(0)
  223. completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue|UNNotificationPresentationOptions.badge.rawValue|UNNotificationPresentationOptions.sound.rawValue))
  224. }
  225. @available(iOS 10.0, *)
  226. func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
  227. let userInfo = response.notification.request.content.userInfo
  228. let request = response.notification.request // 收到推送的请求
  229. let content = request.content // 收到推送的消息内容
  230. let badge = content.badge // 推送消息的角标
  231. let body = content.body // 推送消息体
  232. let sound = content.sound // 推送消息的声音
  233. let subtitle = content.subtitle // 推送消息的副标题
  234. let title = content.title // 推送消息的标题
  235. if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
  236. JPUSHService.handleRemoteNotification(userInfo)
  237. }else{
  238. //判断为本地通知
  239. O2Logger.debug("iOS10 前台收到本地通知:{\nbody:\(body),\ntitle:\(title),\nsubtitle:\(subtitle),\nbadge:\(badge ?? 0),\nsound:\(sound.debugDescription)")
  240. }
  241. UIApplication.shared.applicationIconBadgeNumber = 0
  242. JPUSHService.setBadge(0)
  243. completionHandler()
  244. }
  245. @objc private func updateVersion(_ response:AnyObject?){
  246. O2Logger.debug("update be callbacked")
  247. if let obj = response {
  248. //ProgressHUD.dismiss()
  249. //print(obj)
  250. let appURLString = (obj as! NSDictionary)["downloadURL"]
  251. if let appURL = URL(string: appURLString as! String) {
  252. if UIApplication.shared.canOpenURL(appURL) {
  253. if UIApplication.shared.openURL(appURL) {
  254. PgyUpdateManager.sharedPgy().updateLocalBuildNumber()
  255. }
  256. }
  257. }
  258. }
  259. }
  260. }
  261. //MARK: - JMessage Delegate
  262. extension AppDelegate: JMessageDelegate {
  263. func onDBMigrateStart() {
  264. }
  265. func onDBMigrateFinishedWithError(_ error: Error!) {
  266. // self.showSuccess(title: "数据库升级完成")
  267. }
  268. func onReceive(_ event: JMSGUserLoginStatusChangeEvent!) {
  269. switch event.eventType.rawValue {
  270. // case JMSGLoginStatusChangeEventType.eventNotificationLoginKicked.rawValue:
  271. // DDLogInfo("被踢 重新登录")
  272. // _reLogin()
  273. // break
  274. case JMSGLoginStatusChangeEventType.eventNotificationLoginKicked.rawValue,
  275. JMSGLoginStatusChangeEventType.eventNotificationServerAlterPassword.rawValue,
  276. JMSGLoginStatusChangeEventType.eventNotificationUserLoginStatusUnexpected.rawValue:
  277. DDLogInfo("被踢 重新登录")
  278. _reLogin()
  279. default:
  280. break
  281. }
  282. }
  283. func onReceive(_ event: JMSGFriendNotificationEvent!) {
  284. switch event.eventType.rawValue {
  285. case JMSGFriendEventType.eventNotificationReceiveFriendInvitation.rawValue,
  286. JMSGFriendEventType.eventNotificationAcceptedFriendInvitation.rawValue,
  287. JMSGFriendEventType.eventNotificationDeclinedFriendInvitation.rawValue:
  288. cacheInvitation(event: event)
  289. case JMSGFriendEventType.eventNotificationDeletedFriend.rawValue,
  290. JMSGFriendEventType.eventNotificationReceiveServerFriendUpdate.rawValue:
  291. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
  292. default:
  293. break
  294. }
  295. }
  296. private func cacheInvitation(event: JMSGNotificationEvent) {
  297. let friendEvent = event as! JMSGFriendNotificationEvent
  298. let user = friendEvent.getFromUser()
  299. let reason = friendEvent.getReason()
  300. let info = JCVerificationInfo.create(username: user!.username, nickname: user?.nickname, appkey: user!.appKey!, resaon: reason, state: JCVerificationType.wait.rawValue)
  301. switch event.eventType.rawValue {
  302. case JMSGFriendEventType.eventNotificationReceiveFriendInvitation.rawValue:
  303. info.state = JCVerificationType.receive.rawValue
  304. JCVerificationInfoDB.shareInstance.insertData(info)
  305. case JMSGFriendEventType.eventNotificationAcceptedFriendInvitation.rawValue:
  306. info.state = JCVerificationType.accept.rawValue
  307. JCVerificationInfoDB.shareInstance.updateData(info)
  308. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
  309. case JMSGFriendEventType.eventNotificationDeclinedFriendInvitation.rawValue:
  310. info.state = JCVerificationType.reject.rawValue
  311. JCVerificationInfoDB.shareInstance.updateData(info)
  312. default:
  313. break
  314. }
  315. if UserDefaults.standard.object(forKey: kUnreadInvitationCount) != nil {
  316. let count = UserDefaults.standard.object(forKey: kUnreadInvitationCount) as! Int
  317. UserDefaults.standard.set(count + 1, forKey: kUnreadInvitationCount)
  318. } else {
  319. UserDefaults.standard.set(1, forKey: kUnreadInvitationCount)
  320. }
  321. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
  322. }
  323. func _logout() {
  324. JMSGUser.logout(nil)
  325. JCVerificationInfoDB.shareInstance.queue = nil
  326. UserDefaults.standard.removeObject(forKey: kCurrentUserName)
  327. // let alertView = UIAlertView(title: "您的账号在其它设备上登录", message: "", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "重新登录")
  328. // alertView.show()
  329. }
  330. func _reLogin() {
  331. if let account = O2AuthSDK.shared.myInfo() {
  332. JMSGUser.login(withUsername: account.id!, password: "QazWsxEdc!@#", completionHandler: { (resultObject, errMsg) in
  333. if errMsg == nil {
  334. DDLogInfo("IM登录成功,user = \(String(describing: resultObject))")
  335. }else{
  336. DDLogError("IM登录失改,error = \(String(describing: errMsg))")
  337. }
  338. })
  339. }else {
  340. DDLogError("_reLogin 。。。。。 IM登录失败,error = 当前登录用户为空!!!")
  341. }
  342. }
  343. }