82 lines
2.4 KiB
Swift
82 lines
2.4 KiB
Swift
//
|
|
// BackgroundTaskManager.swift
|
|
// Earthquake Network
|
|
//
|
|
// Created by Andrea Busi on 16/08/23.
|
|
// Copyright © 2023 Earthquake Network. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
import BackgroundTasks
|
|
|
|
|
|
@objc
|
|
class BackgroundTaskManager: NSObject {
|
|
|
|
@objc
|
|
static let shared = BackgroundTaskManager()
|
|
|
|
private let identifiers: [BackgroundTaskIdentifiable.Type] = [UpdateUserLocationTask.self]
|
|
|
|
// MARK: - Public
|
|
|
|
@objc
|
|
func registerTasks() {
|
|
identifiers
|
|
.forEach { taskIdentifiable in
|
|
BGTaskScheduler.shared.register(forTaskWithIdentifier: taskIdentifiable.identifier, using: DispatchQueue.global()) { [weak self] task in
|
|
guard let appTask = task as? BGAppRefreshTask else { return }
|
|
|
|
self?.handleTask(appTask, with: taskIdentifiable)
|
|
self?.scheduleTaskRequest(for: taskIdentifiable)
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Public
|
|
|
|
@objc
|
|
func scheduleUpdateServerPosition() {
|
|
scheduleTaskRequest(for: UpdateUserLocationTask.self)
|
|
}
|
|
|
|
|
|
// MARK: - Private
|
|
|
|
private func scheduleTaskRequest(
|
|
for taskIdentifiable: BackgroundTaskIdentifiable.Type
|
|
) {
|
|
let request = BGAppRefreshTaskRequest(identifier: taskIdentifiable.identifier)
|
|
// Fetch no earlier than X minutes from now
|
|
request.earliestBeginDate = Date(timeIntervalSinceNow: taskIdentifiable.interval)
|
|
//request.requiresNetworkConnectivity = true
|
|
|
|
do {
|
|
try BGTaskScheduler.shared.submit(request)
|
|
print("[BackgroundTaskManager] Background task scheduler submitted")
|
|
} catch {
|
|
print("[BackgroundTaskManager] Could not schedule background taksk. Error: \(error)")
|
|
}
|
|
}
|
|
|
|
private func handleTask(
|
|
_ appTask: BGAppRefreshTask,
|
|
with taskIdentifiable: BackgroundTaskIdentifiable.Type
|
|
) {
|
|
// create a task
|
|
let task = taskIdentifiable.init()
|
|
|
|
// Provide the background task with an expiration handler that cancels the operation.
|
|
appTask.expirationHandler = {
|
|
task.exipration()
|
|
}
|
|
|
|
// Handle workload
|
|
task.handle(appTask) { success in
|
|
// Inform the system that the background task is complete
|
|
// when the operation completes.
|
|
appTask.setTaskCompleted(success: success)
|
|
}
|
|
}
|
|
}
|