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. //极光
  15. let appKey = "9aca7cc20fe0cc987cd913ca"
  16. let bmapKey = "cL9Y2GLhUxgqmKTIcyxv28Y2S7O2DfYj"
  17. let channel = "Publish channel"
  18. let isProduction = true
  19. @UIApplicationMain
  20. class AppDelegate: UIResponder, UIApplicationDelegate,JPUSHRegisterDelegate,UNUserNotificationCenterDelegate {
  21. var _mapManager: BMKMapManager?
  22. var window: UIWindow?
  23. //中心服务器节点类
  24. public static let o2Collect = O2Collect()
  25. //中心服务器绑定数据信息
  26. public static var deviceData = CollectDeviceData()
  27. //网络监听
  28. public let o2ReachabilityManager = O2ReachabilityManager.sharedInstance
  29. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  30. //启动日志管理器
  31. O2Logger.startLogManager()
  32. //日志文件
  33. O2Logger.getLogFiles()
  34. O2Logger.debug("设置运行版本==========,\(PROJECTMODE)")
  35. //网络检查
  36. o2ReachabilityManager.startListening()
  37. //Alamofire
  38. NetworkActivityIndicatorManager.shared.isEnabled = true
  39. //搜索框
  40. UISearchBar.appearance().barTintColor = RGB(251, g: 71, b: 71)
  41. UISearchBar.appearance().tintColor = UIColor.white
  42. UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = RGB(251, g: 71, b: 71)
  43. //设置一个是否第一授权的标志
  44. if #available(iOS 10.0, *){
  45. let center = UNUserNotificationCenter.current()
  46. center.delegate = self
  47. let options:UNAuthorizationOptions = [.badge,.alert,.sound]
  48. center.requestAuthorization(options: options, completionHandler: { (granted, err) in
  49. if granted == true {
  50. //记录已经打开授权
  51. //print("aaaaaaaaaaaa")
  52. AppConfigSettings.shared.notificationGranted = true
  53. AppConfigSettings.shared.firstGranted = true
  54. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  55. }else{
  56. //记录禁用授权
  57. AppConfigSettings.shared.notificationGranted = false
  58. AppConfigSettings.shared.firstGranted = true
  59. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  60. }
  61. })
  62. }else{
  63. let types:UIUserNotificationType = [.badge,.alert,.sound]
  64. let setting = UIUserNotificationSettings(types: types, categories: nil)
  65. UIApplication.shared.registerUserNotificationSettings(setting)
  66. }
  67. //UMessage.setLogEnabled(true)
  68. //蒲公英
  69. let pgyAppId = PGY_APP_ID
  70. PgyManager.shared().themeColor = base_color
  71. PgyManager.shared().feedbackActiveType = KPGYFeedbackActiveType.pgyFeedbackActiveTypeThreeFingersPan
  72. PgyManager.shared().start(withAppId: pgyAppId)
  73. PgyUpdateManager.sharedPgy().start(withAppId: pgyAppId)
  74. if UIDevice.deviceModelReadable() == "Simulator" {
  75. AppDelegate.deviceData.name = UIDevice.idForVendor()!
  76. }
  77. //Buglyy异常上报
  78. Bugly.start(withAppId: "0bc87f457b")
  79. //JPush
  80. _setupJPUSH()
  81. JPUSHService.setup(withOption: launchOptions, appKey: appKey, channel: channel, apsForProduction: isProduction)
  82. JMessage.setupJMessage(launchOptions, appKey: appKey, channel: channel, apsForProduction: isProduction, category: nil, messageRoaming: true)
  83. _setupJMessage()
  84. _mapManager = BMKMapManager()
  85. BMKMapManager.setCoordinateTypeUsedInBaiduMapSDK(BMK_COORDTYPE_BD09LL)
  86. _mapManager?.start(bmapKey, generalDelegate: nil)
  87. JPUSHService.registrationIDCompletionHandler { (resCode, registrationID) in
  88. if resCode == 0 {
  89. O2Logger.debug("registrationID获取成功\(registrationID ?? "")")
  90. //AppDelegate.deviceData.name = registrationID
  91. O2AuthSDK.shared.setDeviceToken(token: registrationID ?? "registrationIDerror0x0x")
  92. }else{
  93. O2Logger.debug("registrationID获取失败,code:\(resCode)")
  94. O2AuthSDK.shared.setDeviceToken(token: registrationID ?? "registrationIDerror0x0x")
  95. }
  96. }
  97. //初始化相关值
  98. //AppDelegate.deviceData.deviceType = "ios"
  99. OOPlusButtonSubclass.register()
  100. OOTabBarHelper.initTabBarStyle()
  101. return true
  102. }
  103. // MARK:- private func Jpush
  104. private func _setupJPUSH() {
  105. if #available(iOS 10, *) {
  106. let entity = JPUSHRegisterEntity()
  107. entity.types = NSInteger(UNAuthorizationOptions.alert.rawValue) |
  108. NSInteger(UNAuthorizationOptions.sound.rawValue) |
  109. NSInteger(UNAuthorizationOptions.badge.rawValue)
  110. JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
  111. } else if #available(iOS 8, *) {
  112. // 可以自定义 categories
  113. JPUSHService.register(
  114. forRemoteNotificationTypes: UIUserNotificationType.badge.rawValue |
  115. UIUserNotificationType.sound.rawValue |
  116. UIUserNotificationType.alert.rawValue,
  117. categories: nil)
  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. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  148. let deviceId = deviceToken.hexString
  149. // if !deviceId.isEmpty {
  150. // AppDelegate.deviceData.name = deviceId
  151. // }else{
  152. // AppDelegate.deviceData.name = "104C9F7F-7403-4B3E-B6A2-C222C82074FF"
  153. // }
  154. O2Logger.debug("get the deviceToken \(deviceToken)")
  155. NotificationCenter.default.post(name: Notification.Name(rawValue: "DidRegisterRemoteNotification"), object: deviceToken)
  156. JPUSHService.registerDeviceToken(deviceToken)
  157. JMessage.registerDeviceToken(deviceToken)
  158. }
  159. func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
  160. if notificationSettings.types.rawValue == 0 {
  161. AppConfigSettings.shared.notificationGranted = false
  162. AppConfigSettings.shared.firstGranted = true
  163. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  164. }else{
  165. AppConfigSettings.shared.notificationGranted = true
  166. AppConfigSettings.shared.firstGranted = true
  167. NotificationCenter.default.post(name: NSNotification.Name.init("SETTING_NOTI"), object: nil)
  168. }
  169. }
  170. func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  171. DDLogError(error.localizedDescription)
  172. AppDelegate.deviceData.name = "104C9F7F-7403-4B3E-B6A2-C222C82074FF"
  173. }
  174. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  175. JPUSHService.handleRemoteNotification(userInfo)
  176. O2Logger.debug("收到通知,\(userInfo)")
  177. NotificationCenter.default.post(name: Notification.Name(rawValue: "AddNotificationCount"), object: nil) //把 要addnotificationcount
  178. }
  179. func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
  180. JPUSHService.showLocalNotification(atFront: notification, identifierKey: nil)
  181. }
  182. func applicationWillResignActive(_ application: UIApplication) {
  183. }
  184. func applicationDidEnterBackground(_ application: UIApplication) {
  185. }
  186. func applicationWillEnterForeground(_ application: UIApplication) {
  187. application.applicationIconBadgeNumber = 0
  188. application.cancelAllLocalNotifications()
  189. }
  190. func applicationDidBecomeActive(_ application: UIApplication) {
  191. if UIDevice.deviceModelReadable() != "Simulator" {
  192. PgyUpdateManager.sharedPgy().checkUpdate(withDelegete: self, selector: #selector(updateVersion(_:)))
  193. }
  194. }
  195. func applicationWillTerminate(_ application: UIApplication) {
  196. }
  197. deinit {
  198. o2ReachabilityManager.stopListening()
  199. }
  200. func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
  201. return true
  202. }
  203. func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
  204. return true
  205. }
  206. @available(iOS 10.0, *)
  207. func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
  208. let userInfo = response.notification.request.content.userInfo
  209. let request = response.notification.request // 收到推送的请求
  210. let content = request.content // 收到推送的消息内容
  211. let badge = content.badge // 推送消息的角标
  212. let body = content.body // 推送消息体
  213. let sound = content.sound // 推送消息的声音
  214. let subtitle = content.subtitle // 推送消息的副标题
  215. let title = content.title // 推送消息的标题
  216. if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
  217. JPUSHService.handleRemoteNotification(userInfo)
  218. }else{
  219. //判断为本地通知
  220. O2Logger.debug("iOS10 前台收到本地通知:{\nbody:\(body),\ntitle:\(title),\nsubtitle:\(subtitle),\nbadge:\(badge ?? 0),\nsound:\(sound.debugDescription)")
  221. }
  222. completionHandler()
  223. }
  224. @available(iOS 10.0, *)
  225. func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!,
  226. withCompletionHandler completionHandler: ((Int) -> Void)!) {
  227. let userInfo = notification.request.content.userInfo
  228. let request = 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 (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. completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue|UNNotificationPresentationOptions.badge.rawValue|UNNotificationPresentationOptions.sound.rawValue))
  242. }
  243. @available(iOS 10.0, *)
  244. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  245. }
  246. @available(iOS 10.0, *)
  247. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  248. }
  249. @objc private func updateVersion(_ response:AnyObject?){
  250. O2Logger.debug("update be callbacked")
  251. if let obj = response {
  252. //ProgressHUD.dismiss()
  253. //print(obj)
  254. let appURLString = (obj as! NSDictionary)["downloadURL"]
  255. if let appURL = URL(string: appURLString as! String) {
  256. if UIApplication.shared.canOpenURL(appURL) {
  257. if UIApplication.shared.openURL(appURL) {
  258. PgyUpdateManager.sharedPgy().updateLocalBuildNumber()
  259. }
  260. }
  261. }
  262. }
  263. }
  264. }
  265. //MARK: - JMessage Delegate
  266. extension AppDelegate: JMessageDelegate {
  267. func onDBMigrateStart() {
  268. ProgressHUD.show("数据库升级中")
  269. }
  270. func onDBMigrateFinishedWithError(_ error: Error!) {
  271. ProgressHUD.showSuccess("数据库升级完成")
  272. }
  273. func onReceive(_ event: JMSGNotificationEvent!) {
  274. switch event.eventType {
  275. case .receiveFriendInvitation, .acceptedFriendInvitation, .declinedFriendInvitation:
  276. cacheInvitation(event: event)
  277. case .loginKicked, .serverAlterPassword, .userLoginStatusUnexpected:
  278. _logout()
  279. case .deletedFriend, .receiveServerFriendUpdate:
  280. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
  281. default:
  282. break
  283. }
  284. }
  285. private func cacheInvitation(event: JMSGNotificationEvent) {
  286. let friendEvent = event as! JMSGFriendNotificationEvent
  287. let user = friendEvent.getFromUser()
  288. let reason = friendEvent.getReason()
  289. let info = JCVerificationInfo.create(username: user!.username, nickname: user?.nickname, appkey: user!.appKey!, resaon: reason, state: JCVerificationType.wait.rawValue)
  290. switch event.eventType {
  291. case .receiveFriendInvitation:
  292. info.state = JCVerificationType.receive.rawValue
  293. JCVerificationInfoDB.shareInstance.insertData(info)
  294. case .acceptedFriendInvitation:
  295. info.state = JCVerificationType.accept.rawValue
  296. JCVerificationInfoDB.shareInstance.updateData(info)
  297. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
  298. case .declinedFriendInvitation:
  299. info.state = JCVerificationType.reject.rawValue
  300. JCVerificationInfoDB.shareInstance.updateData(info)
  301. default:
  302. break
  303. }
  304. if UserDefaults.standard.object(forKey: kUnreadInvitationCount) != nil {
  305. let count = UserDefaults.standard.object(forKey: kUnreadInvitationCount) as! Int
  306. UserDefaults.standard.set(count + 1, forKey: kUnreadInvitationCount)
  307. } else {
  308. UserDefaults.standard.set(1, forKey: kUnreadInvitationCount)
  309. }
  310. NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
  311. }
  312. func _logout() {
  313. JMSGUser.logout(nil)
  314. JCVerificationInfoDB.shareInstance.queue = nil
  315. UserDefaults.standard.removeObject(forKey: kCurrentUserName)
  316. // let alertView = UIAlertView(title: "您的账号在其它设备上登录", message: "", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "重新登录")
  317. // alertView.show()
  318. }
  319. }