I'm trying to execute a background task following the Developer Documentation.
This is my code
import SwiftUI
@main
struct MyAppTest_Watch_AppApp: App {
@Environment(\.scenePhase) var scenePhase
let bs = BackgroundSession()
@SceneBuilder var body: some Scene {
WindowGroup {
ContentView()
}.backgroundTask(.appRefresh("prova")) { context in
print("bg task")
await scheduleTask()
}
.onChange(of: scenePhase) { phase in
switch phase {
case .active:
print("\(#function) REPORTS - App change of scenePhase to ACTIVE")
case .inactive:
print("\(#function) REPORTS - App change of scenePhase Inactive")
case .background:
print("\(#function) REPORTS - App change of scenePhase Background")
WKApplication.shared()
.scheduleBackgroundRefresh(
withPreferredDate: Date.init(timeIntervalSinceNow: 5 * 60.0),
userInfo: "prova" as NSSecureCoding & NSObjectProtocol, scheduledCompletion: schedule)
default:
print("\(#function) REPORTS - App change of scenePhase Default")
}
}
}
func scheduleTask() async {
bs.testSession()
await WKApplication.shared()
.scheduleBackgroundRefresh(
withPreferredDate: Date.init(timeIntervalSinceNow: 5 * 60.0),
userInfo: "prova" as NSSecureCoding & NSObjectProtocol, scheduledCompletion: schedule)
}
func schedule(error: Error?) {
if error != nil {
// Handle the scheduling error.
fatalError("*** An error occurred while scheduling the background refresh task. ***")
}
print("Scheduled!")
}
}
On the simulator the background refresh occurs correctly according to the preferred date and executes the background task, on the real watch it does not.
I also set the app as complication in my watch face.
The device I'm testing the app on is an Apple Watch Serie 7 with watchOS 10.3.
Any idea?