Proyectos de Subversion Iphone Microlearning - Nuevo Interface

Rev

Rev 17 | Rev 23 | 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

//UIResponder, UIApplicationDelegate {

class AppDelegate : NSObject, UIApplicationDelegate {
    private var isSyncInProgress = false
    private var syncAdapter = SyncAdapter()
    private let gcmMessageIDKey = "gcm.message_id"
    private var appData = AppData.sharedInstance


    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()
        }
        
        if let new_uuid = UIDevice.current.identifierForVendor?.uuidString {
           
            let old_uuid = appData.deviceUuid
            if new_uuid != old_uuid {
                var sync = SyncModel()
                sync.type = Constants.SYNC_ADAPTER_TYPE_DEVICE
                sync.data = new_uuid
                
                if SyncDao.sharedInstance.insert(record: sync) > 0 {
                    appData.deviceUuid = new_uuid
                    appData.save()
                    
                    syncAdapter.sync {
                            success in
                    }
                }
            }

        }
              
  
        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()
                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 = token
            sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
            
            if SyncDao.sharedInstance.insert(record: sync) > 0 {
            
                appData.fcmToken = token
                appData.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.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 userNotificationDao = UserNotificationDao.sharedInstance
        let now = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = Constants.FORMAT_DATETIME_SERVICE
        let dateOn = dateFormatter.string(from: now)
                
        let title = userInfo["title"]  as? String ?? ""
        let body = userInfo["body"]  as? String ?? ""
        let url = userInfo["url"] as? String ?? ""
        let command = userInfo["command"] as? String ?? ""
        let new_capsules = Int(userInfo["new_capsules"] as? String ?? "") ?? 0

        var userNotification : UserNotificationModel
        
        userNotification = UserNotificationModel(userUuid: appData.userUuid, title: "userInfo", description: "\(userInfo)", viewed: 0, url: "", addedOn: dateOn)
        userNotificationDao.insert(userNotification: userNotification)
        if command == "signout" {
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_EXIT , object: self, userInfo: nil)
        }
        if command == "content-refresh" {
            let userinfo = ["new_capsules" : String("new_capsules"), "is_foreground" : (isForeground ? "1" : "0")]
            
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_REFRESH_CONTENT , object: self, userInfo: userinfo)
        }
        
        
        if !title.isEmpty && !body.isEmpty {
            
            var userNotification = UserNotificationModel(userUuid: appData.userUuid, title: title, description: description, viewed: 0, url: "", addedOn: dateOn)
            
            
            userNotificationDao.insert(userNotification: userNotification)
            
        }
    }

    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 = token
               sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
               
               if SyncDao.sharedInstance.insert(record: sync) > 0 {
               
                   appData.fcmToken = token
                   appData.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.userInfo

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

    completionHandler()
  }
}