Proyectos de Subversion Iphone Microlearning - Inconcert

Rev

Rev 12 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

//
//  twogetskillsApp.swift
//  twogetskills
//
//  Created by Efrain Yanez Recanatini on 1/12/22.
//

import SwiftUI
import BackgroundTasks


@main
struct TwoGetSkillsApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    @Environment(\.scenePhase) var scenePhase
    
    
    @ObservedObject var syncForeground = SyncForegroundObservableObject()
    private let syncAdapter = SyncAdapter()
    private var appData = AppData.sharedInstance
    
    init() {

      let coloredAppearance = UINavigationBarAppearance()
      coloredAppearance.configureWithOpaqueBackground()
      coloredAppearance.backgroundColor = UIColor(Color("color_app_bar_backgroud"))
      coloredAppearance.titleTextAttributes = [.foregroundColor: Color("color_app_bar_foreground")]
      coloredAppearance.largeTitleTextAttributes = [.foregroundColor: Color("color_app_bar_foreground")]
      coloredAppearance.backButtonAppearance.normal.titleTextAttributes = [.foregroundColor: Color("color_app_bar_foreground")]

      UINavigationBar.appearance().standardAppearance = coloredAppearance
      UINavigationBar.appearance().compactAppearance = coloredAppearance
      UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance

      UINavigationBar.appearance().tintColor = UIColor(Color("color_app_bar_foreground"))
        
      UIPageControl.appearance().currentPageIndicatorTintColor = .systemBlue
      UIPageControl.appearance().pageIndicatorTintColor = .systemGray2
      


      registerBGTasksScheduler()
      scheduleProcess()
      scheduleRefresh()
    }
    
    var body: some Scene {

        WindowGroup {
            MainView()
        }

        .onChange(of: scenePhase) { newScenePhase in
            switch newScenePhase {
                case .active:
                    print("App is active")
                    syncForeground.timer.invalidate()
                    syncForeground.timer = Timer.scheduledTimer(timeInterval: 30.0, target: syncAdapter, selector: #selector(syncAdapter.updateTimerForeground), userInfo: nil, repeats: true)
                    break
                    
                case .inactive:
                  print("App is inactive")
                    syncForeground.timer.invalidate()
                    break
                    
                case .background:
                  print("App is in background")
                    syncForeground.timer.invalidate()
                    break

                @unknown default:
                    print("Oh - interesting: I received an unexpected new value.")
                    syncForeground.timer.invalidate()
                    break
                }
          }
    }
    
    func 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() {
        let request = BGAppRefreshTaskRequest(identifier: Constants.BACKGROUND_TASK_REFRESH)
        request.earliestBeginDate = Date(timeIntervalSinceNow: 10 * 60)
        

            
        do {
             try BGTaskScheduler.shared.submit(request)
        } catch {
            print("Could not schedule app refresh: \(error)")
        }
    }
        
    func 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("Could not schedule processing: \(error)")
        }
    }
        
    func handleProcessTask(task: BGProcessingTask) {
        scheduleProcess()
        
        let syncAdapter = SyncAdapter()
        syncAdapter.sync { success in
            task.setTaskCompleted(success: success)
        }

        /*
        task.expirationHandler = {
            task.setTaskCompleted(success: false)
         }
         */
        task.setTaskCompleted(success: true)
    }
        
    func handleRefreshTask(task: BGAppRefreshTask) {
        scheduleRefresh()
        
        
        
        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)
    }
}


class SyncForegroundObservableObject: ObservableObject
{
    @Published var timer : Timer = Timer()
}