I tried to make a background tasks action, however, it seemed not working at all! I can be able to register the bg fetch but cannot having a perform of bg fetch. Can anyone help me? I also add background modes in the capability.
Here's my code:
import BackgroundTasks
import UserNotifications
//BusArrNotification
@main
struct SGPublicTransportApp: App {
init() {
_ = BackgroundTaskHelper.shared
}
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
@Environment(\.scenePhase) private var scenePhase
@AppStorage("BookTime") private var BookedNotificationTime: String = ""
@AppStorage("specificBusService") private var specificBusService: String = ""
@AppStorage("specificBusStopCode") private var specificBusStopCode: String = ""
var body: some Scene {
WindowGroup {
NavigationStack {
ContentView()
}
}
.onChange(of: scenePhase) { phase in
switch phase {
case .active:
print("Active")
if !BookedNotificationTime.isEmpty {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let time = dateFormatter.date(from: BookedNotificationTime)
let diffs = Calendar.current.dateComponents([.minute, .second], from: Date(), to: time!)
if diffs.minute! <= 0 && diffs.second! <= 0 {
specificBusService = ""
specificBusStopCode = ""
BookedNotificationTime = ""
}
}
case .background:
print("Background")
case .inactive:
print("Inactive")
@unknown default: break
}
}
.backgroundTask(.appRefresh("BusArrNotification")) { context in
// Perform the background task here.
await BackgroundTaskHelper.shared.scheduleBackgroundAppRefresh()
// let _ = await BackgroundTaskHelper.shared.performBackgroundRefresh()
print("HELLLO")
}
}
}
class BackgroundTaskHelper {
static let shared = BackgroundTaskHelper()
@ObservedObject var busDataService = BusDataService()
private init() {
// BGTaskScheduler.shared.register(forTaskWithIdentifier: "BusArrNotification", using: nil) { task in
// self.handleAppRefresh(task: task as! BGAppRefreshTask)
// }
}
func handleAppRefresh(task: BGAppRefreshTask) {
scheduleBackgroundAppRefresh()
task.expirationHandler = {
// Handle the expiration of the background task
}
// Perform the task
let isSuccess = performBackgroundRefresh()
if isSuccess {
task.setTaskCompleted(success: true)
} else {
task.setTaskCompleted(success: false)
}
}
func performBackgroundRefresh() -> Bool {
// Implement your background refresh logic here
busDataService.fetchBusData()
print("*** Background refresh performed! ***")
return true
}
func scheduleBackgroundAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "BusArrNotification")
request.earliestBeginDate = Date(timeIntervalSinceNow: 10) // 15 minutes from now
do {
try BGTaskScheduler.shared.submit(request)
print("*** Scheduled! ***")
} catch {
print("*** An error occurred while scheduling the background refresh task: \(error) ***")
}
}
}