Rev 9 | 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 timer = Timer()private var syncAdapter = SyncAdapter()private let gcmMessageIDKey = "gcm.message_id"private let appData = AppData.sharedInstancestatic var orientationLock = UIInterfaceOrientationMask.portraitfunc application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {return AppDelegate.orientationLock}/*func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {// Called when a new scene session is being created.// Use this method to select a configuration to create the new scene with.return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)}func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {// Called when the user discards a scene session.// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.// Use this method to release any resources that were specific to the discarded scenes, as they will not return.}*/func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {print("registro del dispositivo")NotificationCenter.default.addObserver(self, selector: #selector(receivingNewDevice(n:)), name: Constants.NOTIFICATION_NAME_REGISTER_NEW_DEVICE, object: nil)if let uuid = UIDevice.current.identifierForVendor?.uuidString {let userInfo = ["uuid": uuid]NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_REGISTER_NEW_DEVICE , object: self, userInfo: userInfo)}NotificationCenter.default.addObserver(self, selector: #selector(receivingNewToken(n:)), name: Constants.NOTIFICATION_NAME_REGISTER_NEW_FCM_TOKEN, object: nil)// Remote Notification Enable// Use Firebase library to configure APIsprint("Firebase configuracion")FirebaseApp.configure()UNUserNotificationCenter.current().delegate = selflet authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]UNUserNotificationCenter.current().requestAuthorization(options: authOptions,completionHandler: {_, _ in })Messaging.messaging().delegate = selfprint("Register For Remote Notifications")application.registerForRemoteNotifications()return true;}func handleAppRefreshTask(task: BGAppRefreshTask) {print("Handling task")let syncAdapter = SyncAdapter()syncAdapter.sync{ success in//self.inProgress = false;}scheduleBackgroundSyncExecute()}func scheduleBackgroundSyncExecute(){print("scheduleBackgroundSyncExecute")let syncTask = BGAppRefreshTaskRequest(identifier: Constants.IDENTIFIER_BACKGROUND_PROCESS)syncTask.earliestBeginDate = Date(timeIntervalSinceNow: 60)do {try BGTaskScheduler.shared.submit(syncTask)print("task scheduled")} catch {print("Unable to submit task: \(error.localizedDescription)")}}// Storage of the UID once the notification is received@objc func receivingNewDevice(n: NSNotification){print("receivingNewDevice")if n.userInfo != nil{if let new_uuid = n.userInfo?["uuid"]! as? String {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}}}}}}@objc func receivingNewToken(n: NSNotification){if n.userInfo != nil{if let token = n.userInfo?["token"]! as? String {if !token.isEmpty {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}}}}}}}}//Recibir mensajes@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) {print("message userNotificationCenter iOS 10")let userInfo = notification.request.content.userInfo// With swizzling disabled you must let Messaging know about the message, for Analytics// Messaging.messaging().appDidReceiveMessage(userInfo)// ...// Print full message.print(userInfo)// Change this to your preferred presentation optioncompletionHandler([[.alert, .sound]])}func userNotificationCenter(_ center: UNUserNotificationCenter,didReceive response: UNNotificationResponse,withCompletionHandler completionHandler: @escaping () -> Void) {print("message userNotificationCenter")let userInfo = response.notification.request.content.userInfo// ...// With swizzling disabled you must let Messaging know about the message, for Analytics// Messaging.messaging().appDidReceiveMessage(userInfo)// Print full message.print(userInfo)completionHandler()}}extension AppDelegate: MessagingDelegate {func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {Messaging.messaging().token { token, error inif let error = error {print("Error fetching FCM registration token: \(error)")} else if let token = token {let userInfo = ["token": token]NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_REGISTER_NEW_FCM_TOKEN , object: self, userInfo: userInfo)print("FCM REGISTRATION TOKEN: \(token)")}}}}