Proyectos de Subversion Iphone Microlearning

Rev

Autoría | Ultima modificación | Ver Log |

//
//  AppDelegate.swift
//  twogetskills
//
//  Created by Efrain Yanez Recanatini on 2/23/22.
//

import Foundation
import Firebase
import Messages
import BackgroundTasks

//UIResponder, UIApplicationDelegate {

class AppDelegate : NSObject, UIApplicationDelegate {
    var isSyncInProgress = false
    var database = Database()
    var timer = Timer()
    var syncAdapter = SyncAdapter()
    let gcmMessageIDKey = "gcm.message_id"


    
    /*
    
    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("Creación de las tablas")
        if database.open() != nil {
            database.createTables()
        }
        
        
        print("registro del dispositivo")
        NotificationCenter.default.addObserver(self, selector: #selector(receivingNewDevice(n:)), name: .receivingNewDevice, object: nil)
              
        if let uuid = UIDevice.current.identifierForVendor?.uuidString {
            let userInfo = ["uuid": uuid]
            NotificationCenter.default.post(name: .receivingNewDevice , object: self, userInfo: userInfo)
        }
              
       
        print("Firebase configuracion")
        FirebaseApp.configure()
              
        print("Firebase Token")

        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in }
        )
              
        NotificationCenter.default.addObserver(self, selector: #selector(receivingNewToken(n:)), name: .receivingNewToken, object: nil)
              
        // Remote Notification Enable// Use Firebase library to configure APIs
              
        application.registerForRemoteNotifications()
        Messaging.messaging().delegate = self
        
        
         //Timer temporal
         print("timer foreground")
         timer.invalidate()
         timer = Timer.scheduledTimer(timeInterval: 30.0, target: syncAdapter, selector: #selector(syncAdapter.updateTimer), userInfo: nil, repeats: true)
         
         print("register background task \(Constants.IDENTIFIER_BACKGROUND_PROCESS)")
         BGTaskScheduler.shared.register(
             forTaskWithIdentifier: Constants.IDENTIFIER_BACKGROUND_PROCESS,
           using: nil) { (task) in
             print("Task handler")
             self.handleAppRefreshTask(task: task as! BGAppRefreshTask)
         }
        
        
        
        
        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 preference = Preference.sharedInstance
                    let old_uuid = preference.deviceUuid
                    if new_uuid != old_uuid {
                        var sync = SyncModel()
                        sync.type = Constants.SYNC_ADAPTER_TYPE_DEVICE
                        sync.data = new_uuid
                        
                        if SyncDao().insert(record: sync) > 0 {
                            preference.deviceUuid = new_uuid
                            preference.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 {
                        let preference = Preference.sharedInstance
                        if preference.fcmToken != token  {
                            
                            var sync = SyncModel()
                            sync.data = token
                            sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
                            
                            if SyncDao().insert(record: sync) > 0 {
                            
                                preference.fcmToken = token
                                preference.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) {
    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 option
    completionHandler([[.alert, .sound]])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    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 in
            if let error = error {
                print("Error fetching FCM registration token: \(error)")
            } else if let token = token {
                let userInfo = ["token": token]
                NotificationCenter.default.post(name: .receivingNewToken , object: self, userInfo: userInfo)
                print("FCM REGISTRATION TOKEN: \(token)")
            }
        }
    }
}