How to make WCSession reachable when the watchOS app is running in background with HKWorkoutSession

861 Views Asked by At

My watchOS app uses workout API in order to stay running while the app goes to background. The issue is that WCSession becomes unreachable when the app is in background. However, I'm able to run my code and on some condition, it needs to send a message to the iPhone counterpart app.

The specifics of the app require that user doesn't have to interact with it - if there is a timeout, the watch app should send the message to the phone automatically.

Is this possible to achieve? Thanks.

1

There are 1 best solutions below

3
Dan O'Leary On

I believe the handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) method is what you're looking for. Documentation Link

Without seeing your code I can't be sure what your current progress is, but I have used this method to update watchOS Complications in the background as the user's location changes.

func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
    for task in backgroundTasks {
        if WKExtension.shared().applicationState == .background {
            // Do your background work here.
            if let watchComplication = task as? WKWatchConnectivityRefreshBackgroundTask {
                pendingConnectivityTasks.append(watchComplication)
            }
        }
        task.setTaskCompletedWithSnapshot(true)
    }
    completePendingConnectivityTasksIfNeeded()
}

As a side note I will add if your app is not an actual workout app, it will get rejected during App Review for using a HealthKit workout session.