AppDelegate.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. //启动日志管理器
  30. O2Logger.startLogManager()
  31. //日志文件
  32. O2Logger.getLogFiles()
  33. O2Logger.debug("设置运行版本==========,\(PROJECTMODE)")
  34. //网络检查
  35. o2ReachabilityManager.startListening()
  36. //Alamofire
  37. NetworkActivityIndicatorManager.shared.isEnabled = true
  38. //搜索框
  39. UISearchBar.appearance().barTintColor = RGB(251, g: 71, b: 71)
  40. UISearchBar.appearance().tintColor = UIColor.white
  41. UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = RGB(251, g: 71, b: 71)
  42. //设置一个是否第一授权的标志
  43. if #available(iOS 10.0, *){
  44. let center = UNUserNotificationCenter.current()
  45. center.delegate = self
  46. let options:UNAuthorizationOptions = [.badge,.alert,.sound]
  47. center.requestAuthorization(options: options, completionHandler: { (granted, err) in
  48. if granted == true {
  49. //记录已经打开授权
  50. //print("aaaaaaaaaaaa")
  51. AppConfigSettings.shared.notificationGranted = true
  52. AppConfigSettings.shared.firstGranted = true
  53. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  54. }else{
  55. //记录禁用授权
  56. AppConfigSettings.shared.notificationGranted = false
  57. AppConfigSettings.shared.firstGranted = true
  58. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  59. }
  60. })
  61. }else{
  62. let types:UIUserNotificationType = [.badge,.alert,.sound]
  63. let setting = UIUserNotificationSettings(types: types, categories: nil)
  64. UIApplication.shared.registerUserNotificationSettings(setting)
  65. }
  66. //UMessage.setLogEnabled(true)
  67. //蒲公英
  68. let pgyAppId = PGY_APP_ID
  69. PgyManager.shared().themeColor = base_color
  70. PgyManager.shared().feedbackActiveType = KPGYFeedbackActiveType.pgyFeedbackActiveTypeThreeFingersPan
  71. PgyManager.shared().start(withAppId: pgyAppId)
  72. PgyUpdateManager.sharedPgy().start(withAppId: pgyAppId)
  73. if UIDevice.deviceModelReadable() == "Simulator" {
  74. AppDelegate.deviceData.name = UIDevice.idForVendor()!
  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.setupJMessage(launchOptions, appKey: JPUSH_APP_KEY, channel: JPUSH_channel, apsForProduction: isProduction, category: nil, messageRoaming: true)
  82. _setupJMessage()
  83. _mapManager = BMKMapManager()
  84. BMKMapManager.setCoordinateTypeUsedInBaiduMapSDK(BMK_COORDTYPE_BD09LL)
  85. _mapManager?.start(BAIDU_MAP_KEY, generalDelegate: nil)
  86. JPUSHService.registrationIDCompletionHandler { (resCode, registrationID) in
  87. if resCode == 0 {
  88. O2Logger.debug("registrationID获取成功\(registrationID ?? "")")
  89. //AppDelegate.deviceData.name = 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. if #available(iOS 10, *) {
  105. let entity = JPUSHRegisterEntity()
  106. entity.types = NSInteger(UNAuthorizationOptions.alert.rawValue) |
  107. NSInteger(UNAuthorizationOptions.sound.rawValue) |
  108. NSInteger(UNAuthorizationOptions.badge.rawValue)
  109. JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
  110. } else {
  111. // ios 8 以前 categories 必须为nil
  112. JPUSHService.register(
  113. forRemoteNotificationTypes: UIRemoteNotificationType.badge.rawValue |
  114. UIRemoteNotificationType.sound.rawValue |
  115. UIRemoteNotificationType.alert.rawValue,
  116. categories: nil)
  117. }
  118. }
  119. // MARK: - private func
  120. private func _setupJMessage() {
  121. JMessage.add(self as! JMessageDelegate, with: nil)
  122. // JMessage.setLogOFF()
  123. JMessage.setLogOFF()
  124. // if #available(iOS 8, *) {
  125. // JMessage.register(
  126. // forRemoteNotificationTypes: UIUserNotificationType.badge.rawValue |
  127. // UIUserNotificationType.sound.rawValue |
  128. // UIUserNotificationType.alert.rawValue,
  129. // categories: nil)
  130. // } else {
  131. // // iOS 8 以前 categories 必须为nil
  132. // JMessage.register(
  133. // forRemoteNotificationTypes: UIRemoteNotificationType.badge.rawValue |
  134. // UIRemoteNotificationType.sound.rawValue |
  135. // UIRemoteNotificationType.alert.rawValue,
  136. // categories: nil)
  137. // }
  138. }
  139. override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  140. super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
  141. // let deviceId = deviceToken.hexString
  142. // if !deviceId.isEmpty {
  143. // AppDelegate.deviceData.name = deviceId
  144. // }else{
  145. // AppDelegate.deviceData.name = "104C9F7F-7403-4B3E-B6A2-C222C82074FF"
  146. // }
  147. O2Logger.debug("get the deviceToken \(deviceToken)")
  148. NotificationCenter.default.post(name: Notification.Name(rawValue: "DidRegisterRemoteNotification"), object: deviceToken)
  149. JPUSHService.registerDeviceToken(deviceToken)
  150. JMessage.registerDeviceToken(deviceToken)
  151. }
  152. override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  153. DDLogDebug("open url :\(url.absoluteString)")
  154. return true
  155. }
  156. override func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
  157. if notificationSettings.types.rawValue == 0 {
  158. AppConfigSettings.shared.notificationGranted = false
  159. AppConfigSettings.shared.firstGranted = true
  160. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  161. }else{
  162. AppConfigSettings.shared.notificationGranted = true
  163. AppConfigSettings.shared.firstGranted = true
  164. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  165. }
  166. }
  167. override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  168. DDLogError(error.localizedDescription)
  169. AppDelegate.deviceData.name = "104C9F7F-7403-4B3E-B6A2-C222C82074FF"
  170. }
  171. override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  172. JPUSHService.handleRemoteNotification(userInfo)
  173. O2Logger.debug("收到通知,\(userInfo)")
  174. NotificationCenter.default.post(name: Notification.Name(rawValue: "AddNotificationCount"), object: nil) //把 要addnotificationcount
  175. }
  176. override func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
  177. JPUSHService.showLocalNotification(atFront: notification, identifierKey: nil)
  178. }
  179. override func applicationWillEnterForeground(_ application: UIApplication) {
  180. application.applicationIconBadgeNumber = 0
  181. application.cancelAllLocalNotifications()
  182. }
  183. override func applicationDidBecomeActive(_ application: UIApplication) {
  184. if UIDevice.deviceModelReadable() != "Simulator" {
  185. PgyUpdateManager.sharedPgy().checkUpdate(withDelegete: self, selector: #selector(updateVersion(_:)))
  186. }
  187. }
  188. deinit {
  189. o2ReachabilityManager.stopListening()
  190. }
  191. @available(iOS 10.0, *)
  192. func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
  193. let userInfo = response.notification.request.content.userInfo
  194. let request = response.notification.request // 收到推送的请求
  195. let content = request.content // 收到推送的消息内容
  196. let badge = content.badge // 推送消息的角标
  197. let body = content.body // 推送消息体
  198. let sound = content.sound // 推送消息的声音
  199. let subtitle = content.subtitle // 推送消息的副标题
  200. let title = content.title // 推送消息的标题
  201. if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
  202. JPUSHService.handleRemoteNotification(userInfo)
  203. }else{
  204. //判断为本地通知
  205. O2Logger.debug("iOS10 前台收到本地通知:{\nbody:\(body),\ntitle:\(title),\nsubtitle:\(subtitle),\nbadge:\(badge ?? 0),\nsound:\(sound.debugDescription)")
  206. }
  207. completionHandler()
  208. }
  209. @available(iOS 10.0, *)
  210. func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!,
  211. withCompletionHandler completionHandler: ((Int) -> Void)!) {
  212. let userInfo = notification.request.content.userInfo
  213. let request = notification.request // 收到推送的请求
  214. let content = request.content // 收到推送的消息内容
  215. let badge = content.badge // 推送消息的角标
  216. let body = content.body // 推送消息体
  217. let sound = content.sound // 推送消息的声音
  218. let subtitle = content.subtitle // 推送消息的副标题
  219. let title = content.title // 推送消息的标题
  220. if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
  221. JPUSHService.handleRemoteNotification(userInfo)
  222. }else{
  223. //判断为本地通知
  224. O2Logger.debug("iOS10 前台收到本地通知:{\nbody:\(body),\ntitle:\(title),\nsubtitle:\(subtitle),\nbadge:\(badge ?? 0),\nsound:\(sound.debugDescription)")
  225. }
  226. completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue|UNNotificationPresentationOptions.badge.rawValue|UNNotificationPresentationOptions.sound.rawValue))
  227. }
  228. @available(iOS 10.0, *)
  229. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  230. }
  231. @available(iOS 10.0, *)
  232. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  233. }
  234. @objc private func updateVersion(_ response:AnyObject?){
  235. O2Logger.debug("update be callbacked")
  236. if let obj = response {
  237. //ProgressHUD.dismiss()
  238. //print(obj)
  239. let appURLString = (obj as! NSDictionary)["downloadURL"]
  240. if let appURL = URL(string: appURLString as! String) {
  241. if UIApplication.shared.canOpenURL(appURL) {
  242. if UIApplication.shared.openURL(appURL) {
  243. PgyUpdateManager.sharedPgy().updateLocalBuildNumber()
  244. }
  245. }
  246. }
  247. }
  248. }
  249. }
  250. //MARK: - JMessage Delegate
  251. extension AppDelegate: JMessageDelegate {
  252. func onDBMigrateStart() {
  253. // self.showMessage(title: "数据库升级中")
  254. }
  255. func onDBMigrateFinishedWithError(_ error: Error!) {
  256. // self.showSuccess(title: "数据库升级完成")
  257. }
  258. func onReceive(_ event: JMSGNotificationEvent!) {
  259. switch event.eventType {
  260. case .receiveFriendInvitation, .acceptedFriendInvitation, .declinedFriendInvitation:
  261. cacheInvitation(event: event)
  262. case .loginKicked, .serverAlterPassword, .userLoginStatusUnexpected:
  263. _logout()
  264. case .deletedFriend, .receiveServerFriendUpdate:
  265. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
  266. default:
  267. break
  268. }
  269. }
  270. private func cacheInvitation(event: JMSGNotificationEvent) {
  271. let friendEvent = event as! JMSGFriendNotificationEvent
  272. let user = friendEvent.getFromUser()
  273. let reason = friendEvent.getReason()
  274. let info = JCVerificationInfo.create(username: user!.username, nickname: user?.nickname, appkey: user!.appKey!, resaon: reason, state: JCVerificationType.wait.rawValue)
  275. switch event.eventType {
  276. case .receiveFriendInvitation:
  277. info.state = JCVerificationType.receive.rawValue
  278. JCVerificationInfoDB.shareInstance.insertData(info)
  279. case .acceptedFriendInvitation:
  280. info.state = JCVerificationType.accept.rawValue
  281. JCVerificationInfoDB.shareInstance.updateData(info)
  282. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
  283. case .declinedFriendInvitation:
  284. info.state = JCVerificationType.reject.rawValue
  285. JCVerificationInfoDB.shareInstance.updateData(info)
  286. default:
  287. break
  288. }
  289. if UserDefaults.standard.object(forKey: kUnreadInvitationCount) != nil {
  290. let count = UserDefaults.standard.object(forKey: kUnreadInvitationCount) as! Int
  291. UserDefaults.standard.set(count + 1, forKey: kUnreadInvitationCount)
  292. } else {
  293. UserDefaults.standard.set(1, forKey: kUnreadInvitationCount)
  294. }
  295. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
  296. }
  297. func _logout() {
  298. JMSGUser.logout(nil)
  299. JCVerificationInfoDB.shareInstance.queue = nil
  300. UserDefaults.standard.removeObject(forKey: kCurrentUserName)
  301. // let alertView = UIAlertView(title: "您的账号在其它设备上登录", message: "", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "重新登录")
  302. // alertView.show()
  303. }
  304. }