简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM