How to Build a Workout App on Watchos with Audio Feedback

Playing audio in a WatchKit workout app when backgrounded and screen is off

Ahhh, finally I found this post and realised I had the same problem:

The AVAudioSession category needs to be set to AVAudioSessionCategoryPlayback (I had it set to ambient).

As soon as I changed the session category to AVAudioSessionCategoryPlayback it worked!

WatchKit: How to trigger active background app like Music App on Watch other than HKWorkoutSession?

There is a very short list of reasons your app is allowed in the background.

From the documentation:

  • Use an HKWorkoutSession object to start and stop workouts.

  • Use the AVAudioSession class to play extended audio files in the
    background.

  • Use a CLLocationManager object to start a continuous background
    location session.

If your app doesn't do any of those things then it's not allowed to function in the background for more than a few seconds.

An alternative is using Background Tasks, which allows your app to execute some tasks either on a schedule or as a response to connectivity updates. Background Tasks, however, doesn't mean that your app can remain open like with background sessions.

Setting up WatchKit for a workout app

Here is the code you need. Heart rate is updated every 5 seconds when you start a workout.
https://github.com/coolioxlr/watchOS-3-heartrate

No haptic feedback

As an addition to my previous answer I created a sample project that shows how to trigger vibrations while in the background:

For a full example on how to use HKWorkoutSession check out my sample project on GitHub. The sample app will trigger a vibration every five seconds even with the app running in the background.
HKWorkoutSession and thus the sample only work when the app was signed with a provisioning profile containing the HealthKit entitlement. Be sure to change the Development Team to your own Team for all three available targets. Xcode will try to create the needed provisioning profiles. If there are any signing issues or you use a wildcard provisioning profile running in the background will not work.

is there anyway to keep my WatchKit app running in the background?

Yes, your can. There are several ways:

  1. Start a workout using HKWorkoutSession - the most powerful way, however you need to use HealthKit and only 1 app on the Apple Watch can run this way.
  2. Play audio in the background using WKAudioFilePlayer - only for audio.
  3. WKURLSessionRefreshBackgroundTask suitable for short background refreshes.
  4. There are other background tasks, such as WKSnapshotRefreshBackgroundTask or WKURLSessionRefreshBackgroundTask. They are listed in Background Tasks section of this article.
  5. performExpiringActivity(withReason:using:) can be used to shortly prolong life of the app when it goes to the background.

Also, read Leveraging iOS Technologies.



Related Topics



Leave a reply



Submit