I was using BGAppRefreshTask instead of BGProcessingTask which was the issue. I am still in need of assistance implementing BGProcessingTask. I have the code below:
BGTaskScheduler.shared.register(forTaskWithIdentifier: taskID, using: .main) { task in
self.preformTask(task: task as! BGProcessingTask)
}
func preformTask(task: BGProcessingTask) {
self.isAppRefreshScheduled = false
let swiftTask = Task {
let success = await self.updateNow()
print("Success \(success)")
task.setTaskCompleted(success: true)
task.expirationHandler = nil
}
task.expirationHandler = {
swiftTask.cancel()
}
func updateNow() async {
do {
if self.isUpdating { return }
self.isUpdating = true
defer { self.isUpdating = false }
try await Task.sleep(for: .seconds(3))
UserDefaults.standard.set("taskCompleted", forKey: "test")
print("Task")
self.lastUpdate = .now
} catch {
// discard errors
}
}
func scheduleTask() {
UserDefaults.standard.set("taskScheduled", forKey: "test")
if self.isAppRefreshScheduled {
self.log.debug("will not schedule, already scheduled")
return
}
self.isAppRefreshScheduled = true
do {
self.log.debug("will schedule, task: \(self.routineResetID, privacy: .public)")
let request = BGAppRefreshTaskRequest(
identifier: taskID
)
request.earliestBeginDate = Date(timeIntervalSinceNow: 1)
try BGTaskScheduler.shared.submit(request)
print(request)
} catch {
// discard errors
}
}
.onAppear() {
let testVal = UserDefaults.standard.string(forKey: "test") ?? "default"
print(testVal)
backgroundRefreshModel.scheduleTask()
}
I'm not sure if that's the proper implementation. If it's not, what needs to be changed?
To test this, I'm calling scheduleTask() in onAppear() in ContentView which runs. I set a UserDefaults variable to "taskScheduled" and in updateNow() I set that variable to "taskCompleted". "taskScheduled" prints in onAppear() when loading the app, but after a minute of the app being in the background and opening it again nothing prints. I thought that after closing and opening the app onAppear() would run. Is that an implementation error or is there another function for that purpose?
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags: