Hello,
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 though, when the app is started.
import SwiftUI
import WatchKit
@main
struct WatchApp: App {
@WKExtensionDelegateAdaptor(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, WKExtensionDelegate {
@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?