Proyectos de Subversion Iphone Microlearning - Inconcert

Rev

Rev 15 | 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 Foundation
import Firebase
import Messages
import BackgroundTasks
import SwiftUI

//UIResponder, UIApplicationDelegate {

class AppDelegate : NSObject, UIApplicationDelegate {

    private let gcmMessageIDKey = "gcm.message_id"
    private var appData = AppData.sharedInstance
    public static var orientationLock = UIInterfaceOrientationMask.portrait
    

    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return AppDelegate.orientationLock
    }
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
        [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        /*        let database = Database.sharedInstance
        if database.open() != nil  {
            database.createTables()
        }
        
        */
        
        /*
        for  fontFamily in  UIFont.familyNames {
            for fontName in UIFont.fontNames(forFamilyName: fontFamily) {
                print("\(fontName)")
            }
        }*/
        
    /*        print("observador del UUID del dispositivo")
        NotificationCenter.default.addObserver(self, selector: #selector(receivingNewDevice(n:)), name: Constants.NOTIFICATION_NAME_DEVICE_REGISTER_NAME, object: nil)

        print("observador del FCM TOKEN")
        NotificationCenter.default.addObserver(self, selector: #selector(receivingNewToken(n:)), name: Constants.NOTIFICATION_NAME_FCM_REGISTER_NAME, object: nil)
        */
        
        
        
        
              
  
        FirebaseApp.configure()

        Messaging.messaging().delegate = self

        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let 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()
        
        
        
        registerBGTasksScheduler()
        scheduleProcess()
        scheduleRefresh()
        
        return true
    }
    
    // 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.deviceUuid
                    if new_uuid != old_uuid {
                        
                        var sync = SyncModel()
                        sync.type = Constants.SYNC_ADAPTER_TYPE_DEVICE
                        sync.data = new_uuid
                            
                        let syncDao = SyncDao()
                        if syncDao.insert(record: sync) > 0 {
                            appData.deviceUuid = new_uuid
                            appData.save()
                                
                            syncAdapter.sync(isForeground: true) {
                                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 = token
                            sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
                                
                            let syncDao = SyncDao()
                            if syncDao.insert(record: sync) > 0 {
                                appData.fcmToken = token
                                appData.save()
                                    
                                syncAdapter.sync(isForeground: true) {
                                    success in
                                }
                            }

                        }
                   }
               }
           }
        }*/
    
    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)
    }
    
    func registerBGTasksScheduler() {
        print("background :  registerBGTasksScheduler");
        BGTaskScheduler.shared.register(forTaskWithIdentifier: Constants.BACKGROUND_TASK_REFRESH, using: nil) { task in
                 self.handleRefreshTask(task: task as! BGAppRefreshTask)
        }
        
        BGTaskScheduler.shared.register(forTaskWithIdentifier: Constants.BACKGROUND_TASK_PROCESS, using: nil) { task in
                 self.handleProcessTask(task: task as! BGProcessingTask)
        }

    }
        
    func scheduleRefresh() {
        print("background: scheduleRefresh")
        let request = BGAppRefreshTaskRequest(identifier: Constants.BACKGROUND_TASK_REFRESH)
        request.earliestBeginDate = Date(timeIntervalSinceNow: 10 * 60)
        

            
        do {
             try BGTaskScheduler.shared.submit(request)
        } catch {
            print("background: Could not schedule app refresh: \(error)")
        }
    }
        
    func scheduleProcess() {
        print("background: scheduleProcess")
        let request = BGProcessingTaskRequest(identifier: Constants.BACKGROUND_TASK_PROCESS)
        request.earliestBeginDate = Date(timeIntervalSinceNow: 10 * 60)
        request.requiresNetworkConnectivity = true
        request.requiresExternalPower = false

        do {
            try BGTaskScheduler.shared.submit(request)
        } catch {
            print("background: Could not schedule processing: \(error)")
        }
    }
        
    func handleProcessTask(task: BGProcessingTask) {
        scheduleProcess()
        print("background: handleProcessTask")
        
        let syncAdapter = SyncAdapter()
        syncAdapter.sync(isForeground: false) { success in
            task.setTaskCompleted(success: success)
        }

        task.setTaskCompleted(success: true)
    }
        
    func handleRefreshTask(task: BGAppRefreshTask) {
        scheduleRefresh()
        
        print("background: handleRefreshTask")
        
        let syncAdapter = SyncAdapter()
        if syncAdapter.isCheckChangesRequired() {
            syncAdapter.checkChanges(isForeground: false) { success in
                task.setTaskCompleted(success: success)
            }
        } else {
            task.expirationHandler = {
                task.setTaskCompleted(success: false)
             }
        }
        
 
        task.setTaskCompleted(success: true)
    }
    

    
}

extension AppDelegate: MessagingDelegate {
    
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {

  
        let token = fcmToken ?? ""
        print( "MessagingDelegate didReceiveRegistrationToken: \(token)")
        
        let userInfo = ["token": token]
        NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_FCM_REGISTER_NAME , object: self, userInfo: userInfo)
        

        
    }
}

@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
    
    if 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_YMD
        
        let timeFormatter = DateFormatter()
        timeFormatter.dateFormat = Constants.FORMAT_TIME_12

        
        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 ?? "") ?? 0

    
        if command == "signout" {
            let userinfo = [
                "is_foreground" : (isForeground ? "1" : "0")
            ]
            
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_EXIT , object: self, userInfo: userinfo)
        }
        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)
        

        let userInfo = ["token": token]
        NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_FCM_REGISTER_NAME , object: self, userInfo: userInfo)

    }
    
    

    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.userInfo

    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID from userNotificationCenter didReceive: \(messageID)")
    }
    
    
    processNotification(userInfo: userInfo, isForeground: true)

    completionHandler()
  }
}