Rev 1 | Rev 12 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
//// AppDelegate.swift// twogetskills//// Created by Efrain Yanez Recanatini on 2/23/22.//import Foundationimport Firebaseimport Messagesimport BackgroundTasks//UIResponder, UIApplicationDelegate {class AppDelegate : NSObject, UIApplicationDelegate {private var isSyncInProgress = falseprivate var syncAdapter = SyncAdapter()private let gcmMessageIDKey = "gcm.message_id"private var appData = AppData.sharedInstancestatic var orientationLock = UIInterfaceOrientationMask.portraitfunc application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {return AppDelegate.orientationLock}func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {let database = Database.sharedInstanceif database.open() != nil {database.createTables()}if let new_uuid = UIDevice.current.identifierForVendor?.uuidString {let old_uuid = appData.deviceUuidif new_uuid != old_uuid {var sync = SyncModel()sync.type = Constants.SYNC_ADAPTER_TYPE_DEVICEsync.data = new_uuidif SyncDao.sharedInstance.insert(record: sync) > 0 {appData.deviceUuid = new_uuidappData.save()syncAdapter.sync {success in}}}}FirebaseApp.configure()Messaging.messaging().delegate = selfif #available(iOS 10.0, *) {// For iOS 10 display notification (sent via APNS)UNUserNotificationCenter.current().delegate = selflet authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]UNUserNotificationCenter.current().requestAuthorization(options: authOptions,completionHandler: {_, _ in })} else {let settings: UIUserNotificationSettings =UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)application.registerUserNotificationSettings(settings)}application.registerForRemoteNotifications()return true}func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {if let messageID = userInfo[gcmMessageIDKey] {print("Message ID: \(messageID)")}processNotification(userInfo: userInfo, isForeground: false)completionHandler(UIBackgroundFetchResult.newData)}}extension AppDelegate: MessagingDelegate {func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {let token = fcmToken ?? ""print("token: ", token)if appData.fcmToken != token {var sync = SyncModel()sync.data = tokensync.type = Constants.SYNC_ADAPTER_TYPE_FCMif SyncDao.sharedInstance.insert(record: sync) > 0 {appData.fcmToken = tokenappData.save()syncAdapter.sync {success in}}}}}@available(iOS 10, *)extension AppDelegate : UNUserNotificationCenterDelegate {// Receive displayed notifications for iOS 10 devices.func userNotificationCenter(_ center: UNUserNotificationCenter,willPresent notification: UNNotification,withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {let userInfo = notification.request.content.userInfoif let messageID = userInfo[gcmMessageIDKey] {print("Message ID: \(messageID)")}processNotification(userInfo: userInfo, isForeground: true)completionHandler([[.banner, .badge, .sound]])}private func processNotification(userInfo : [AnyHashable : Any], isForeground : Bool) {let now = Date()let dateFormatter = DateFormatter()dateFormatter.dateFormat = Constants.FORMAT_DATE_YMDlet timeFormatter = DateFormatter()timeFormatter.dateFormat = Constants.FORMAT_TIME_12/*let dateOn = dateFormatter.string(from: now)let timeOn = dateFormatter.string(from: now)let userNotificationDao = UserNotificationDao.sharedInstancevar userNotification : UserNotificationModelif Config.DEBUG && !appData.userUuid.isEmpty {userNotification = UserNotificationModel(userUuid: appData.userUuid, title: "userInfo", body: "\(userInfo)", viewed: 0, url: "", dateOn: dateOn, timeOn: timeOn)userNotificationDao.insert(userNotification: userNotification)}*/guard let apsDict = userInfo["aps"]as?[String:Any] else {return}guard let alertDict = apsDict["alert"]as?[String:Any]else {return}let title = alertDict["title"] as? String ?? ""let body = alertDict["body"] as? String ?? ""let url = userInfo.index(forKey: "url") == nil ? "" : userInfo["url"] as? String ?? ""let command = userInfo.index(forKey: "command") == nil ? "" : userInfo["command"] as? String ?? ""let newCapsules = userInfo.index(forKey: "new_capsules") == nil ? 0 : Int(userInfo["new_capsules"] as? String ?? "") ?? 0if command == "signout" {NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_EXIT , object: self, userInfo: nil)}else if command == "content-refresh" {let userinfo = ["title" : title,"body" : body,"new_capsules" : String(newCapsules),"is_foreground" : (isForeground ? "1" : "0")]NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_REFRESH_CONTENT , object: self, userInfo: userinfo)} else {let userinfo = ["title" : title,"body" : body,"url" : url,]NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_PUSH , object: self, userInfo: userInfo)}}func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {print( "didRegisterForRemoteNotificationsWithDeviceToken")let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }let token = tokenParts.joined()print("token: ", token)if appData.fcmToken != token {var sync = SyncModel()sync.data = tokensync.type = Constants.SYNC_ADAPTER_TYPE_FCMif SyncDao.sharedInstance.insert(record: sync) > 0 {appData.fcmToken = tokenappData.save()syncAdapter.sync {success in}}}}func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {print( "didFailToRegisterForRemoteNotificationsWithError")}func userNotificationCenter(_ center: UNUserNotificationCenter,didReceive response: UNNotificationResponse,withCompletionHandler completionHandler: @escaping () -> Void) {let userInfo = response.notification.request.content.userInfoif let messageID = userInfo[gcmMessageIDKey] {print("Message ID from userNotificationCenter didReceive: \(messageID)")}processNotification(userInfo: userInfo, isForeground: true)completionHandler()}}