AppDelegate.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. //
  2. // AppDelegate.swift
  3. // WisdomCampusApk
  4. //
  5. // Created by 方楚豪 on 2021/11/21.
  6. //
  7. import UIKit
  8. import WebKit
  9. import UserNotifications
  10. import MMKV
  11. import AVFoundation
  12. import ImSDK_Plus
  13. import YJNetManager
  14. @main
  15. class AppDelegate: UIResponder, UIApplicationDelegate,V2TIMAPNSListener,V2TIMConversationListener {
  16. var isForceLandscape:Bool = false
  17. var isForcePortrait:Bool = false
  18. var isForceAllDerictions:Bool = false //支持所有方向
  19. static var PUSH_URL:String? = nil
  20. var soundId: SystemSoundID?
  21. //static var LOADING_VIEW: LoadingView = LoadingView.init(frame: CGRect.init())
  22. //注册音频文件,获取SystemSoundID
  23. func getSoundId() -> SystemSoundID {
  24. var soundId: SystemSoundID = SystemSoundID()
  25. let path = Bundle.main.path(forResource: "sound", ofType: "m4a")
  26. let url = URL.init(fileURLWithPath: path!)
  27. AudioServicesCreateSystemSoundID(url as CFURL, &soundId)
  28. return soundId
  29. }
  30. //播放自定义铃声和震动
  31. func playAlertSound() {
  32. if soundId == nil {
  33. soundId = self.getSoundId()
  34. }
  35. AudioServicesAddSystemSoundCompletion(soundId!, nil, nil, { (SystemSoundID, pointer: UnsafeMutableRawPointer?) in
  36. AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
  37. AudioServicesPlaySystemSound(SystemSoundID)
  38. }, nil)
  39. //kSystemSoundID_Vibrate是震动的id
  40. AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
  41. AudioServicesPlaySystemSound(soundId!)
  42. }
  43. //停止播放
  44. func stopAlertSoundWithSoundID() {
  45. if soundId != nil {
  46. AudioServicesDisposeSystemSoundID(soundId!)
  47. AudioServicesRemoveSystemSoundCompletion(soundId!)
  48. soundId = nil
  49. }
  50. AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate)
  51. }
  52. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  53. V2TIMManager.sharedInstance().setAPNSListener(self)
  54. V2TIMManager.sharedInstance().addConversationListener(listener: self)
  55. registerForPushNotifications()
  56. YJNetMonitoring.share().start()
  57. YJNetMonitoring.share().checkNetCanUse()
  58. MMKV.initialize()
  59. if launchOptions != nil {
  60. let userInfo:[String:Any?] = launchOptions![UIApplication.LaunchOptionsKey.remoteNotification] as! [String : Any?]
  61. if (userInfo["ext"] != nil) {
  62. let ext = userInfo["ext"] as! String
  63. let extDict = ext.toDictionary()
  64. if extDict["toUrl"] != nil {
  65. AppDelegate.PUSH_URL = (userInfo["ext"] as! String)
  66. print("\(AppDelegate.PUSH_URL!)")
  67. }
  68. }
  69. }
  70. // 注册后台播放
  71. let session = AVAudioSession.sharedInstance()
  72. do {
  73. try session.setActive(true)
  74. try session.setCategory(AVAudioSession.Category.playback)
  75. }catch {
  76. print(error)
  77. }
  78. UIApplication.shared.beginReceivingRemoteControlEvents()
  79. //UIApplication.openAppSettings()
  80. return true
  81. }
  82. func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  83. if url.scheme != nil && url.scheme! == "lancoowsc" {
  84. let urlComponents = NSURLComponents(string: url.absoluteString)
  85. let queryItems = urlComponents?.queryItems
  86. for item in queryItems! {
  87. if item.name == "toUrl" {
  88. MMKV.default()?.set(item.value!, forKey: "scheme_to_url")
  89. }else {
  90. var milliStamp : String {
  91. let millisecond = Date().milliStamp
  92. return "\(millisecond)"
  93. }
  94. MMKV.default()?.set("\(milliStamp)_\(String(describing: item.value))", forKey: item.name)
  95. }
  96. }
  97. }
  98. return true
  99. }
  100. // MARK: UISceneSession Lifecycle
  101. func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
  102. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  103. }
  104. func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
  105. }
  106. /// 设置屏幕支持的方向
  107. func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
  108. if isForceAllDerictions == true {
  109. return .all
  110. } else if isForceLandscape == true {
  111. return .landscape
  112. } else if isForcePortrait == true {
  113. return .portrait
  114. }
  115. return .portrait
  116. }
  117. static var initalTime:Int64 = 0
  118. func showMainViewController() {
  119. AppDelegate.initalTime = Int64(Date().timeIntervalSince1970)
  120. let callingContactViewController = MainController.init()
  121. V2TIMManager.sharedInstance().add(callingContactViewController)
  122. V2TIMManager.sharedInstance().addSignalingListener(listener: callingContactViewController)
  123. V2TIMManager.sharedInstance().addAdvancedMsgListener(listener: callingContactViewController)
  124. let rootVC = UINavigationController.init(rootViewController: callingContactViewController)
  125. if let keyWindow = SceneDelegate.getCurrentWindow() {
  126. keyWindow.rootViewController = rootVC
  127. keyWindow.makeKeyAndVisible()
  128. }
  129. }
  130. public static var deviceToken:Data = Data.init()
  131. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  132. print("接收消息:\(userInfo)")
  133. }
  134. static var unreadNumber:Int = 0
  135. // 未读数发生变化后保存未读数
  136. func onTotalUnreadMessageCountChanged(_ totalUnreadCount: UInt64) {
  137. AppDelegate.unreadNumber = 0
  138. }
  139. // APP 推到后台后上报自定义未读数
  140. func onSetAPPUnreadCount() -> UInt32 {
  141. return 0;
  142. }
  143. }
  144. extension AppDelegate {
  145. func getNotificationSettings() {
  146. UNUserNotificationCenter.current().getNotificationSettings { settings in
  147. print("Notification settings: \(settings)")
  148. guard settings.authorizationStatus == .authorized else { return }
  149. DispatchQueue.main.async {
  150. UIApplication.shared.registerForRemoteNotifications()
  151. }
  152. }
  153. }
  154. func registerForPushNotifications() {
  155. UNUserNotificationCenter.current()
  156. .requestAuthorization(options: [.alert, .sound, .badge]) {
  157. [weak self] granted, error in
  158. print("Permission granted: \(granted)")
  159. guard granted else { return }
  160. self?.getNotificationSettings()
  161. }
  162. UNUserNotificationCenter.current().delegate = self
  163. }
  164. // MARK: - <1>
  165. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  166. // 将devicetoken发送给服务端
  167. let deviceTokenString = deviceToken.reduce("",{$0 + String(format:"%02x",$1)})
  168. print("deviceTokenString:\(deviceTokenString)")
  169. AppDelegate.deviceToken = deviceToken
  170. }
  171. func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  172. print("didFailToRegisterForRemoteNotificationsWithError-error = \(error)")
  173. }
  174. func applicationWillTerminate(_ application: UIApplication) {
  175. // APP被杀死,清除APP和浏览器缓存
  176. let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
  177. let fileArr = FileManager.default.subpaths(atPath: cachePath!)
  178. for file in fileArr! {
  179. let path = (cachePath! as NSString).appending("/\(file)")
  180. if FileManager.default.fileExists(atPath: path) {
  181. do {
  182. try FileManager.default.removeItem(atPath: path)
  183. } catch {}
  184. }
  185. }
  186. let dataStore = WKWebsiteDataStore.default()
  187. dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), completionHandler: { (records) in
  188. for record in records{
  189. WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {
  190. print("清除成功\(record)")
  191. })
  192. }
  193. })
  194. }
  195. }
  196. extension AppDelegate: UNUserNotificationCenterDelegate {
  197. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
  198. print("Handle push from foreground")
  199. // custom code to handle push while app is in the foreground
  200. print("\(notification.request.content.userInfo)")
  201. print("\(notification.request.content.title)")
  202. completionHandler([.badge, .sound, .banner, .list])
  203. }
  204. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  205. print("Handle push from background or closed");
  206. // if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
  207. if (response.notification.request.content.userInfo["ext"] != nil) {
  208. let ext = response.notification.request.content.userInfo["ext"] as! String
  209. let extDict = ext.toDictionary()
  210. if extDict["toUrl"] != nil {
  211. AppDelegate.PUSH_URL = extDict["toUrl"] as? String
  212. print("\(AppDelegate.PUSH_URL!)")
  213. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  214. //show main vc
  215. AppUtils.shared.showMainController()
  216. }
  217. }
  218. }
  219. }
  220. }
  221. extension UIApplication {
  222. @objc class func openAppSettings() {
  223. shared.open(URL(string: openSettingsURLString)!,
  224. options: [:],
  225. completionHandler: nil)
  226. }
  227. }
  228. extension Date {
  229. /// 获取当前 秒级 时间戳 - 10位
  230. var timeStamp : String {
  231. let timeInterval: TimeInterval = self.timeIntervalSince1970
  232. let timeStamp = Int(timeInterval)
  233. return "\(timeStamp)"
  234. }
  235. /// 获取当前 毫秒级 时间戳 - 13位
  236. var milliStamp : String {
  237. let timeInterval: TimeInterval = self.timeIntervalSince1970
  238. print("timeInterval:\(timeInterval)")
  239. let millisecond = CLongLong(round(timeInterval*1000))
  240. return "\(millisecond)"
  241. }
  242. }