chrizzel85
chrizzel85

Reputation: 1

WatchOS background task does not trigger

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

Upvotes: 0

Views: 273

Answers (1)

Drew Westcott
Drew Westcott

Reputation: 576

Has your App got a complication? On watchOS your App will only be woken in the background if there is a running complication on the current watch face.

The page you are following states: 'For the system to allocate background execution time to your app, your app must have a complication on the active watch face. If the system gives your app background execution time, it attempts to trigger your background task no earlier than the time specified by the withPreferredDate parameter; however, depending on the watch’s state, the system can defer or throttle your tasks. Therefore, your app might not wake up exactly at the specified time.'

Upvotes: 1

Related Questions