// // AppDelegate.swift // WisdomCampusApk // // Created by 方楚豪 on 2021/11/21. // import UIKit import WebKit import UserNotifications import MMKV import AVFoundation import ImSDK_Plus import YJNetManager @main class AppDelegate: UIResponder, UIApplicationDelegate,V2TIMAPNSListener,V2TIMConversationListener { var isForceLandscape:Bool = false var isForcePortrait:Bool = false var isForceAllDerictions:Bool = false //支持所有方向 static var PUSH_URL:String? = nil var soundId: SystemSoundID? //static var LOADING_VIEW: LoadingView = LoadingView.init(frame: CGRect.init()) //注册音频文件,获取SystemSoundID func getSoundId() -> SystemSoundID { var soundId: SystemSoundID = SystemSoundID() let path = Bundle.main.path(forResource: "sound", ofType: "m4a") let url = URL.init(fileURLWithPath: path!) AudioServicesCreateSystemSoundID(url as CFURL, &soundId) return soundId } //播放自定义铃声和震动 func playAlertSound() { if soundId == nil { soundId = self.getSoundId() } AudioServicesAddSystemSoundCompletion(soundId!, nil, nil, { (SystemSoundID, pointer: UnsafeMutableRawPointer?) in AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) AudioServicesPlaySystemSound(SystemSoundID) }, nil) //kSystemSoundID_Vibrate是震动的id AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) AudioServicesPlaySystemSound(soundId!) } //停止播放 func stopAlertSoundWithSoundID() { if soundId != nil { AudioServicesDisposeSystemSoundID(soundId!) AudioServicesRemoveSystemSoundCompletion(soundId!) soundId = nil } AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate) } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { V2TIMManager.sharedInstance().setAPNSListener(self) V2TIMManager.sharedInstance().addConversationListener(listener: self) registerForPushNotifications() YJNetMonitoring.share().start() YJNetMonitoring.share().checkNetCanUse() MMKV.initialize() if launchOptions != nil { let userInfo:[String:Any?] = launchOptions![UIApplication.LaunchOptionsKey.remoteNotification] as! [String : Any?] if (userInfo["ext"] != nil) { let ext = userInfo["ext"] as! String let extDict = ext.toDictionary() if extDict["toUrl"] != nil { AppDelegate.PUSH_URL = (userInfo["ext"] as! String) print("\(AppDelegate.PUSH_URL!)") } } } // 注册后台播放 let session = AVAudioSession.sharedInstance() do { try session.setActive(true) try session.setCategory(AVAudioSession.Category.playback) }catch { print(error) } UIApplication.shared.beginReceivingRemoteControlEvents() //UIApplication.openAppSettings() return true } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { if url.scheme != nil && url.scheme! == "lancoowsc" { let urlComponents = NSURLComponents(string: url.absoluteString) let queryItems = urlComponents?.queryItems for item in queryItems! { if item.name == "toUrl" { MMKV.default()?.set(item.value!, forKey: "scheme_to_url") }else { var milliStamp : String { let millisecond = Date().milliStamp return "\(millisecond)" } MMKV.default()?.set("\(milliStamp)_\(String(describing: item.value))", forKey: item.name) } } } return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { } /// 设置屏幕支持的方向 func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { if isForceAllDerictions == true { return .all } else if isForceLandscape == true { return .landscape } else if isForcePortrait == true { return .portrait } return .portrait } static var initalTime:Int64 = 0 func showMainViewController() { AppDelegate.initalTime = Int64(Date().timeIntervalSince1970) let callingContactViewController = MainController.init() V2TIMManager.sharedInstance().add(callingContactViewController) V2TIMManager.sharedInstance().addSignalingListener(listener: callingContactViewController) V2TIMManager.sharedInstance().addAdvancedMsgListener(listener: callingContactViewController) let rootVC = UINavigationController.init(rootViewController: callingContactViewController) if let keyWindow = SceneDelegate.getCurrentWindow() { keyWindow.rootViewController = rootVC keyWindow.makeKeyAndVisible() } } public static var deviceToken:Data = Data.init() func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { print("接收消息:\(userInfo)") } static var unreadNumber:Int = 0 // 未读数发生变化后保存未读数 func onTotalUnreadMessageCountChanged(_ totalUnreadCount: UInt64) { AppDelegate.unreadNumber = 0 } // APP 推到后台后上报自定义未读数 func onSetAPPUnreadCount() -> UInt32 { return 0; } } extension AppDelegate { func getNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { settings in print("Notification settings: \(settings)") guard settings.authorizationStatus == .authorized else { return } DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } func registerForPushNotifications() { UNUserNotificationCenter.current() .requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, error in print("Permission granted: \(granted)") guard granted else { return } self?.getNotificationSettings() } UNUserNotificationCenter.current().delegate = self } // MARK: - <1> func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // 将devicetoken发送给服务端 let deviceTokenString = deviceToken.reduce("",{$0 + String(format:"%02x",$1)}) print("deviceTokenString:\(deviceTokenString)") AppDelegate.deviceToken = deviceToken } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("didFailToRegisterForRemoteNotificationsWithError-error = \(error)") } func applicationWillTerminate(_ application: UIApplication) { // APP被杀死,清除APP和浏览器缓存 let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first let fileArr = FileManager.default.subpaths(atPath: cachePath!) for file in fileArr! { let path = (cachePath! as NSString).appending("/\(file)") if FileManager.default.fileExists(atPath: path) { do { try FileManager.default.removeItem(atPath: path) } catch {} } } let dataStore = WKWebsiteDataStore.default() dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), completionHandler: { (records) in for record in records{ WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: { print("清除成功\(record)") }) } }) } } extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) { print("Handle push from foreground") // custom code to handle push while app is in the foreground print("\(notification.request.content.userInfo)") print("\(notification.request.content.title)") completionHandler([.badge, .sound, .banner, .list]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("Handle push from background or closed"); // if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background if (response.notification.request.content.userInfo["ext"] != nil) { let ext = response.notification.request.content.userInfo["ext"] as! String let extDict = ext.toDictionary() if extDict["toUrl"] != nil { AppDelegate.PUSH_URL = extDict["toUrl"] as? String print("\(AppDelegate.PUSH_URL!)") DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { //show main vc AppUtils.shared.showMainController() } } } } } extension UIApplication { @objc class func openAppSettings() { shared.open(URL(string: openSettingsURLString)!, options: [:], completionHandler: nil) } } extension Date { /// 获取当前 秒级 时间戳 - 10位 var timeStamp : String { let timeInterval: TimeInterval = self.timeIntervalSince1970 let timeStamp = Int(timeInterval) return "\(timeStamp)" } /// 获取当前 毫秒级 时间戳 - 13位 var milliStamp : String { let timeInterval: TimeInterval = self.timeIntervalSince1970 print("timeInterval:\(timeInterval)") let millisecond = CLongLong(round(timeInterval*1000)) return "\(millisecond)" } }