I have an Apple Watch app, that should perform a background task.
I have set up the delegate and using SwiftUIs background task .appRefresh.
But for some reason it never triggers.
The scheduler is executed correctly, when the app is started.
import SwiftUI
import WatchKit
@main
struct WatchApp: App {
@WKApplicationDelegateAdaptor(ExtensionDelegate.self) var delegate
@ObservedObject var hostingModel = HostingModel.shared
var body: some Scene {
WindowGroup {
ContentView()
}
.backgroundTask(.appRefresh) { context in
print("background task")
await hostingModel.fetchAll()
}
}
}
class ExtensionDelegate: NSObject, WKApplicationDelegate {
@ObservedObject var hostingModel = HostingModel.shared
func applicationDidFinishLaunching() {
}
func applicationDidBecomeActive() {
hostingModel.scheduleBackgroundRefresh()
}
func applicationDidEnterBackground() {
print("in background")
}
// I believe it`s not needed this is just for debugging
private func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) async {
print("handle")
await hostingModel.fetchAll()
}
}
func scheduleBackgroundRefresh() {
WKApplication.shared()
.scheduleBackgroundRefresh(
withPreferredDate: Date.init(timeIntervalSinceNow: 15 * 60.0),
userInfo: nil) { error in
if error != nil {
// Handle the scheduling error.
fatalError("*** An error occurred while scheduling the background refresh task. ***")
}
print("*** Scheduled! ***")
}
}
Am I missing something?
I would like to trigger a task on my Watch app in the background.
This task fetches some data, stores it in KeyChain to provide it to the Complications.
I followed this way from the official docs, but the task is never executed.
Apple Developer – Using Background Tasks