AppDelegate.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 EZSwiftExtensions
  12. import UserNotifications
  13. import O2OA_Auth_SDK
  14. import Flutter
  15. import IQKeyboardManagerSwift
  16. let isProduction = true
  17. @UIApplicationMain
  18. class AppDelegate: FlutterAppDelegate, JPUSHRegisterDelegate, UNUserNotificationCenterDelegate {
  19. var _mapManager: BMKMapManager?
  20. //中心服务器节点类
  21. public static let o2Collect = O2Collect()
  22. //中心服务器绑定数据信息
  23. public static var deviceData = CollectDeviceData()
  24. //网络监听
  25. public let o2ReachabilityManager = O2ReachabilityManager.sharedInstance
  26. // flutter engine
  27. var flutterEngine : FlutterEngine?
  28. override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  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. //设置一个是否第一授权的标志
  51. if #available(iOS 10.0, *){
  52. let center = UNUserNotificationCenter.current()
  53. center.delegate = self
  54. let options:UNAuthorizationOptions = [.badge,.alert,.sound]
  55. center.requestAuthorization(options: options, completionHandler: { (granted, err) in
  56. if granted == true {
  57. //记录已经打开授权
  58. //print("aaaaaaaaaaaa")
  59. AppConfigSettings.shared.notificationGranted = true
  60. AppConfigSettings.shared.firstGranted = true
  61. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  62. }else{
  63. //记录禁用授权
  64. AppConfigSettings.shared.notificationGranted = false
  65. AppConfigSettings.shared.firstGranted = true
  66. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  67. }
  68. })
  69. }else{
  70. let types:UIUserNotificationType = [.badge,.alert,.sound]
  71. let setting = UIUserNotificationSettings(types: types, categories: nil)
  72. UIApplication.shared.registerUserNotificationSettings(setting)
  73. }
  74. //UMessage.setLogEnabled(true)
  75. //蒲公英
  76. let pgyAppId = PGY_APP_ID
  77. PgyManager.shared().themeColor = base_color
  78. PgyManager.shared().feedbackActiveType = KPGYFeedbackActiveType.pgyFeedbackActiveTypeThreeFingersPan
  79. PgyManager.shared().start(withAppId: pgyAppId)
  80. PgyUpdateManager.sharedPgy().start(withAppId: pgyAppId)
  81. if UIDevice.deviceModelReadable() == "Simulator" {
  82. AppDelegate.deviceData.name = UIDevice.idForVendor()!
  83. }
  84. //Buglyy异常上报
  85. Bugly.start(withAppId: BUGLY_ID)
  86. //JPush
  87. _setupJPUSH()
  88. JPUSHService.setup(withOption: launchOptions, appKey: JPUSH_APP_KEY, channel: JPUSH_channel, apsForProduction: isProduction)
  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. if #available(iOS 10, *) {
  113. let entity = JPUSHRegisterEntity()
  114. entity.types = NSInteger(UNAuthorizationOptions.alert.rawValue) |
  115. NSInteger(UNAuthorizationOptions.sound.rawValue) |
  116. NSInteger(UNAuthorizationOptions.badge.rawValue)
  117. JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
  118. } else {
  119. // ios 8 以前 categories 必须为nil
  120. JPUSHService.register(
  121. forRemoteNotificationTypes: UIRemoteNotificationType.badge.rawValue |
  122. UIRemoteNotificationType.sound.rawValue |
  123. UIRemoteNotificationType.alert.rawValue,
  124. categories: nil)
  125. }
  126. }
  127. // MARK: - private func
  128. private func _setupJMessage() {
  129. JMessage.add(self as! JMessageDelegate, with: nil)
  130. // JMessage.setLogOFF()
  131. JMessage.setLogOFF()
  132. // if #available(iOS 8, *) {
  133. // JMessage.register(
  134. // forRemoteNotificationTypes: UIUserNotificationType.badge.rawValue |
  135. // UIUserNotificationType.sound.rawValue |
  136. // UIUserNotificationType.alert.rawValue,
  137. // categories: nil)
  138. // } else {
  139. // // iOS 8 以前 categories 必须为nil
  140. // JMessage.register(
  141. // forRemoteNotificationTypes: UIRemoteNotificationType.badge.rawValue |
  142. // UIRemoteNotificationType.sound.rawValue |
  143. // UIRemoteNotificationType.alert.rawValue,
  144. // categories: nil)
  145. // }
  146. }
  147. override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  148. super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
  149. // let deviceId = deviceToken.hexString
  150. // if !deviceId.isEmpty {
  151. // AppDelegate.deviceData.name = deviceId
  152. // }else{
  153. // AppDelegate.deviceData.name = "104C9F7F-7403-4B3E-B6A2-C222C82074FF"
  154. // }
  155. O2Logger.debug("get the deviceToken \(deviceToken)")
  156. NotificationCenter.default.post(name: Notification.Name(rawValue: "DidRegisterRemoteNotification"), object: deviceToken)
  157. JPUSHService.registerDeviceToken(deviceToken)
  158. JMessage.registerDeviceToken(deviceToken)
  159. }
  160. override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  161. DDLogDebug("open url :\(url.absoluteString)")
  162. return true
  163. }
  164. override func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
  165. if notificationSettings.types.rawValue == 0 {
  166. AppConfigSettings.shared.notificationGranted = false
  167. AppConfigSettings.shared.firstGranted = true
  168. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  169. }else{
  170. AppConfigSettings.shared.notificationGranted = true
  171. AppConfigSettings.shared.firstGranted = true
  172. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  173. }
  174. }
  175. override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  176. DDLogError(error.localizedDescription)
  177. AppDelegate.deviceData.name = "104C9F7F-7403-4B3E-B6A2-C222C82074FF"
  178. }
  179. override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  180. JPUSHService.handleRemoteNotification(userInfo)
  181. O2Logger.debug("收到通知,\(userInfo)")
  182. NotificationCenter.default.post(name: Notification.Name(rawValue: "AddNotificationCount"), object: nil) //把 要addnotificationcount
  183. }
  184. override func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
  185. JPUSHService.showLocalNotification(atFront: notification, identifierKey: nil)
  186. }
  187. override func applicationWillEnterForeground(_ application: UIApplication) {
  188. application.applicationIconBadgeNumber = 0
  189. application.cancelAllLocalNotifications()
  190. }
  191. override func applicationDidBecomeActive(_ application: UIApplication) {
  192. if UIDevice.deviceModelReadable() != "Simulator" {
  193. PgyUpdateManager.sharedPgy().checkUpdate(withDelegete: self, selector: #selector(updateVersion(_:)))
  194. }
  195. }
  196. deinit {
  197. o2ReachabilityManager.stopListening()
  198. }
  199. @available(iOS 10.0, *)
  200. func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
  201. let userInfo = response.notification.request.content.userInfo
  202. let request = response.notification.request // 收到推送的请求
  203. let content = request.content // 收到推送的消息内容
  204. let badge = content.badge // 推送消息的角标
  205. let body = content.body // 推送消息体
  206. let sound = content.sound // 推送消息的声音
  207. let subtitle = content.subtitle // 推送消息的副标题
  208. let title = content.title // 推送消息的标题
  209. if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
  210. JPUSHService.handleRemoteNotification(userInfo)
  211. }else{
  212. //判断为本地通知
  213. O2Logger.debug("iOS10 前台收到本地通知:{\nbody:\(body),\ntitle:\(title),\nsubtitle:\(subtitle),\nbadge:\(badge ?? 0),\nsound:\(sound.debugDescription)")
  214. }
  215. completionHandler()
  216. }
  217. @available(iOS 10.0, *)
  218. func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!,
  219. withCompletionHandler completionHandler: ((Int) -> Void)!) {
  220. let userInfo = notification.request.content.userInfo
  221. let request = notification.request // 收到推送的请求
  222. let content = request.content // 收到推送的消息内容
  223. let badge = content.badge // 推送消息的角标
  224. let body = content.body // 推送消息体
  225. let sound = content.sound // 推送消息的声音
  226. let subtitle = content.subtitle // 推送消息的副标题
  227. let title = content.title // 推送消息的标题
  228. if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
  229. JPUSHService.handleRemoteNotification(userInfo)
  230. }else{
  231. //判断为本地通知
  232. O2Logger.debug("iOS10 前台收到本地通知:{\nbody:\(body),\ntitle:\(title),\nsubtitle:\(subtitle),\nbadge:\(badge ?? 0),\nsound:\(sound.debugDescription)")
  233. }
  234. completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue|UNNotificationPresentationOptions.badge.rawValue|UNNotificationPresentationOptions.sound.rawValue))
  235. }
  236. @available(iOS 10.0, *)
  237. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  238. }
  239. @available(iOS 10.0, *)
  240. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  241. }
  242. @objc private func updateVersion(_ response:AnyObject?){
  243. O2Logger.debug("update be callbacked")
  244. if let obj = response {
  245. //ProgressHUD.dismiss()
  246. //print(obj)
  247. let appURLString = (obj as! NSDictionary)["downloadURL"]
  248. if let appURL = URL(string: appURLString as! String) {
  249. if UIApplication.shared.canOpenURL(appURL) {
  250. if UIApplication.shared.openURL(appURL) {
  251. PgyUpdateManager.sharedPgy().updateLocalBuildNumber()
  252. }
  253. }
  254. }
  255. }
  256. }
  257. }
  258. //MARK: - JMessage Delegate
  259. extension AppDelegate: JMessageDelegate {
  260. func onDBMigrateStart() {
  261. // self.showMessage(title: "数据库升级中")
  262. }
  263. func onDBMigrateFinishedWithError(_ error: Error!) {
  264. // self.showSuccess(title: "数据库升级完成")
  265. }
  266. func onReceive(_ event: JMSGNotificationEvent!) {
  267. switch event.eventType {
  268. case .receiveFriendInvitation, .acceptedFriendInvitation, .declinedFriendInvitation:
  269. cacheInvitation(event: event)
  270. case .loginKicked, .serverAlterPassword, .userLoginStatusUnexpected:
  271. _logout()
  272. case .deletedFriend, .receiveServerFriendUpdate:
  273. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
  274. default:
  275. break
  276. }
  277. }
  278. private func cacheInvitation(event: JMSGNotificationEvent) {
  279. let friendEvent = event as! JMSGFriendNotificationEvent
  280. let user = friendEvent.getFromUser()
  281. let reason = friendEvent.getReason()
  282. let info = JCVerificationInfo.create(username: user!.username, nickname: user?.nickname, appkey: user!.appKey!, resaon: reason, state: JCVerificationType.wait.rawValue)
  283. switch event.eventType {
  284. case .receiveFriendInvitation:
  285. info.state = JCVerificationType.receive.rawValue
  286. JCVerificationInfoDB.shareInstance.insertData(info)
  287. case .acceptedFriendInvitation:
  288. info.state = JCVerificationType.accept.rawValue
  289. JCVerificationInfoDB.shareInstance.updateData(info)
  290. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
  291. case .declinedFriendInvitation:
  292. info.state = JCVerificationType.reject.rawValue
  293. JCVerificationInfoDB.shareInstance.updateData(info)
  294. default:
  295. break
  296. }
  297. if UserDefaults.standard.object(forKey: kUnreadInvitationCount) != nil {
  298. let count = UserDefaults.standard.object(forKey: kUnreadInvitationCount) as! Int
  299. UserDefaults.standard.set(count + 1, forKey: kUnreadInvitationCount)
  300. } else {
  301. UserDefaults.standard.set(1, forKey: kUnreadInvitationCount)
  302. }
  303. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
  304. }
  305. func _logout() {
  306. JMSGUser.logout(nil)
  307. JCVerificationInfoDB.shareInstance.queue = nil
  308. UserDefaults.standard.removeObject(forKey: kCurrentUserName)
  309. // let alertView = UIAlertView(title: "您的账号在其它设备上登录", message: "", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "重新登录")
  310. // alertView.show()
  311. }
  312. }