WorkoutKit

RSS for tag

The WorkoutKit framework provides the ability to create, preview, and schedule planned workouts for the Workout app on Apple Watch.

WorkoutKit Documentation

Posts under WorkoutKit tag

30 Posts
Sort by:
Post not yet marked as solved
1 Replies
67 Views
Hello, I’m currently developing a fitness app for watchOS that lets a user to manually set a desired heart rate target zone (enter numbers representing the lower and upper boundaries) and start a workout (right now it’s only “Other” type). After that my app monitors user’s heart rate and alerts them when they’re out of zone. When user ends the workout, the info about this workout appears on “Fitness” iOS app, and user can see the workout data like Workout Time, Active and Total Calories, Avg. Heart Rate. Also user can see Heart Rate chart with info how their heart rate was changing during a workout (see the Figure 1). Now to the question. When user clicks “Show More” button above the Heart Rate chart, they can see the same Heart Rate chart and another one, with Post-Workout Heart Rate (see the Figure 2). But there is no “Estimated time in each heart rate zone” as one can see in the workout’s details that were recorded from Apple’s workout (watchOS “Workout” app, for a workout of “Other” type as well). Please see the Figure 3. The question is: is it possible to add “Estimated time in each heart rate zone” to workout recorded via my third-party app so it would look like on the Figure 3 in "Fitness" iOS app, and if it's possible, what steps should I undertake to implement this ? Thanks in advance! I posted the screenshots in the replies to the post, because otherwise I was not able to submit a post ("sensitive language" warning, I suspect it's because of the ids in the attached screenshot's urls)
Posted Last updated
.
Post not yet marked as solved
0 Replies
51 Views
Hello, I am using the project from https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/building_a_multidevice_workout_app The workout is starting on the watch and I can see the metrics, but it seems the mirroring with the phone is not working, I am getting this errors [mirroring] <HKWorkoutSession:0x600002c10100 57C340BA-2AA9-4477-9AC8-181698A526A5 running [Primary]>: Failed to send data to remote session with error: Error Domain=com.apple.healthkit Code=300 "Remote device is unreachable" UserInfo={NSLocalizedDescription=Remote device is unreachable, NSUnderlyingError=0x600000c53b70 {Error Domain=RPErrorDomain Code=-6727 "kNotFoundErr ('rapport:rdid:PairedCompanion' not found)" UserInfo={cuErrorDesc=kNotFoundErr ('rapport:rdid:PairedCompanion' not found), cuErrorMsg='rapport:rdid:PairedCompanion' not found, NSLocalizedDescription=kNotFoundErr ('rapport:rdid:PairedCompanion' not found)}}} Does anybody else has this issue? Thank you
Posted
by Mausa.
Last updated
.
Post not yet marked as solved
0 Replies
67 Views
The WWDC23 session number 10016 is referring to a way to generate .workout files (timecode 09:43) in both binary and JSON format. Unfortunately, the API seems to have changed: CustomWorkoutComposition renamed to CustomWorkout .dataRepresentation disappeared Ideally I would like to generate .workout files directly in JSON format but there is no specifications published and no documentation to generate them. Any idea where I should look?
Posted
by Juliensnz.
Last updated
.
Post not yet marked as solved
0 Replies
218 Views
Hello fellow developers, I've recently developed a workout companion watch app for iOS. However, I'm now have a task of implementing custom workouts for my app. I've come across a video demonstrating how to create and schedule custom workouts for the watch app, which I believe will be incredibly helpful for my project. Video Link: Creating Custom Workouts for iOS Watch App If anyone knows of any additional resources, such as articles or videos, that further explores this topic, I would greatly appreciate it if you could share them with me. Thank you for your assistance! Best regards, Pranit Bhogale
Posted Last updated
.
Post not yet marked as solved
0 Replies
255 Views
Please reference the Sample Planner app which can be found at the below link. https://developer.apple.com/documentation/WorkoutKit/customizing-workouts-with-workoutkit. In WorkoutStore.swift, all of the values are hard coded. I would like to turn them into variables stored in @EnvironmentObject (WorkoutStoreValue). With the below code, using "singleRunStartDelay" as a trial, I can get that variable passed to the WorkStore struct only when the app is first opened, however, I have not been able to get it changed in realtime. I need help with changing the WorkoutStore struct to have the values updated in realtime. I have tried changing the func from static but that gives an error (Instance member 'createSingleRunWorkout' cannot be used on type 'WorkoutStore'; did you mean to use a value of this type instead?) I'm now learning Xcode/SwiftUI. I have been stuck for about four day trying many different ideas. Thanks // Copyright © 2024 Apple. All rights reserved. /* The structure that returns running workout compositions. */ import HealthKit import WorkoutKit import SwiftUI import Foundation struct WorkoutStore{ @EnvironmentObject var workoutStoreValue: WorkoutStoreValue static func createSingleRunWorkout() -> CustomWorkout { let getReadyStep = WorkoutStep(goal: .open) //fixed to .open let singleRunDelay = WorkoutStoreValue.shared.singleRunStartDelay var onYourMarkStep = IntervalStep(.work) onYourMarkStep.step.goal = .time(Double(singleRunDelay), .seconds) //you have this much time to start var runStep = IntervalStep(.work) runStep.step.goal = .distance(100, .meters) //hard coded for now. Need to insert distance variable here runStep.step.alert = .speed(3...4, unit: .metersPerSecond, metric: .current) // Would like to insert alert variables here var block = IntervalBlock() block.steps = [ onYourMarkStep, runStep ] block.iterations = 1 //fixed at 1. Would like to insert as a variable return CustomWorkout(activity: .running, location: .outdoor, displayName: "Single run mode", warmup: getReadyStep, blocks: [block]) } }
Posted
by Leroy439.
Last updated
.
Post not yet marked as solved
0 Replies
339 Views
Hi experts, I got an Ultra2 a while ago and has been using it on walking / running exercise. Recently I came across to this apple site: debug profile and I'm curious about what I would get during the exercise. So I follow the instruction and install the location services profile. After getting the sysdiagnose report, I try to get location related information from it. And it seems that the log from "locationd" and "gpsd" are what I'm looking for. But when I try to look into the nmea information, I found out the sysdiagnose only provide around 10-15 mins of nmea data. For example, let's say I have a walking exercise from 0900 - 1000, but I can only see nmea data from 0945 - 1000. The data from 0900 to 0945 can't be found in the sysdiagnose. Not sure if's the limitation or any setting I can change to increase the logging period? Thanks.
Posted Last updated
.
Post not yet marked as solved
0 Replies
350 Views
Hi there, I'm new here, looking for a step-by-step tutorial that will help me to achieve my first step. https://developer.apple.com/documentation/workoutkit/customizing-workouts-with-workoutkit downloaded the WorkoutKit sample file. try to run, and connect to my account and team but get an error to connect a device. Your team has no devices from which to generate a provisioning profile. Connect a device to use or manually add device IDs in Certificates, Identifiers & Profiles. https://developer.apple.com/account/ " I logged in to my web account but didn't find any device IDs in Certificates, Identifiers & Profiles section
Posted
by aroesti.
Last updated
.
Post not yet marked as solved
2 Replies
334 Views
Hi. is it possible to create a Custom Workout with different activity types. I want a Custom Workout where the user first has to run and after do skiing. Its like a little bit like SwimBikeRun but with running and Skiing. How can i do this? Thank you
Posted
by boerni.
Last updated
.
Post not yet marked as solved
0 Replies
381 Views
Hello, it is discussed here https://developer.apple.com/videos/play/wwdc2023/10016/ (12:16) regarding WorkoutComposition, but unfortunately, I cannot find this class or structure in the documentation. Has this concept been removed?
Posted
by zikomiko.
Last updated
.
Post not yet marked as solved
0 Replies
316 Views
With CustomWorkout, I can assign a name (displayName) to workouts, which also appears in the Workout app. Unfortunately, this parameter is missing for common workouts such as SingleGoalWorkout. Is there a reason for this? I find it inconvenient when the name is missing CustomWorkout init(activity: HKWorkoutActivityType, location: HKWorkoutSessionLocationType, displayName: String?, warmup: WorkoutStep?, blocks: [IntervalBlock], cooldown: WorkoutStep?) SingleGoalWorkout init(activity: HKWorkoutActivityType, location: HKWorkoutSessionLocationType, swimmingLocation: HKWorkoutSwimmingLocationType, goal: WorkoutGoal)
Posted
by zikomiko.
Last updated
.
Post not yet marked as solved
0 Replies
393 Views
https://idmsa.apple.com/IDMSWebAuth/signin?path=%2F%2Fforums%2Fpost%2Fquestion%3Flogin%3Dtrue&language=US-EN&instanceId=EN&appIdKey=25138a77e3499638936f018102a53961c923f72b517d4a4d6aee9f09529baca9&rv=4 I've built and tested the code obtained from this site, but although the session starts, pausing or stopping it doesn't seem to work properly. Does anyone know what might be causing this issue? I'm using the latest versions of iOS and watchOS, and my Xcode is version 15.0.1. The main code is as follows, and the session does not start properly in startWorkout. import Foundation import os import HealthKit @MainActor class WorkoutManager: NSObject, ObservableObject { struct SessionSateChange { let newState: HKWorkoutSessionState let date: Date } @Published var sessionState: HKWorkoutSessionState = .notStarted @Published var heartRate: Double = 0 @Published var activeEnergy: Double = 0 @Published var speed: Double = 0 @Published var power: Double = 0 @Published var cadence: Double = 0 @Published var distance: Double = 0 @Published var water: Double = 0 @Published var elapsedTimeInterval: TimeInterval = 0 @Published var workout: HKWorkout? let typesToShare: Set = [HKQuantityType.workoutType(), HKQuantityType(.dietaryWater)] let typesToRead: Set = [ HKQuantityType(.heartRate), HKQuantityType(.activeEnergyBurned), HKQuantityType(.distanceWalkingRunning), HKQuantityType(.cyclingSpeed), HKQuantityType(.cyclingPower), HKQuantityType(.cyclingCadence), HKQuantityType(.distanceCycling), HKQuantityType(.dietaryWater), HKQuantityType.workoutType(), HKObjectType.activitySummaryType() ] let healthStore = HKHealthStore() var session: HKWorkoutSession? #if os(watchOS) var builder: HKLiveWorkoutBuilder? #else var contextDate: Date? #endif let asynStreamTuple = AsyncStream.makeStream(of: SessionSateChange.self, bufferingPolicy: .bufferingNewest(1)) static let shared = WorkoutManager() private override init() { super.init() Task { for await value in asynStreamTuple.stream { await consumeSessionStateChange(value) } } } /** Consume the session state change from the async stream to update sessionState and finish the workout. */ private func consumeSessionStateChange(_ change: SessionSateChange) async { sessionState = change.newState /** Wait for the session to transition states before ending the builder. */ #if os(watchOS) /** Send the elapsed time to the iOS side. */ let elapsedTimeInterval = session?.associatedWorkoutBuilder().elapsedTime(at: change.date) ?? 0 let elapsedTime = WorkoutElapsedTime(timeInterval: elapsedTimeInterval, date: change.date) if let elapsedTimeData = try? JSONEncoder().encode(elapsedTime) { await sendData(elapsedTimeData) } guard change.newState == .stopped, let builder else { return } let finishedWorkout: HKWorkout? do { try await builder.endCollection(at: change.date) finishedWorkout = try await builder.finishWorkout() session?.end() } catch { Logger.shared.log("Failed to end workout: \(error))") return } workout = finishedWorkout #endif } } // MARK: - Workout session management // extension WorkoutManager { func resetWorkout() { #if os(watchOS) builder = nil #endif workout = nil session = nil activeEnergy = 0 heartRate = 0 distance = 0 water = 0 power = 0 cadence = 0 speed = 0 sessionState = .notStarted } func sendData(_ data: Data) async { do { try await session?.sendToRemoteWorkoutSession(data: data) } catch { Logger.shared.log("Failed to send data: \(error)") } } } extension WorkoutManager: HKWorkoutSessionDelegate { nonisolated func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) { Logger.shared.log("Session state changed from \(fromState.rawValue) to \(toState.rawValue)") let sessionSateChange = SessionSateChange(newState: toState, date: date) asynStreamTuple.continuation.yield(sessionSateChange) } nonisolated func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) { Logger.shared.log("\(#function): \(error)") } nonisolated func workoutSession(_ workoutSession: HKWorkoutSession, didDisconnectFromRemoteDeviceWithError error: Error?) { Logger.shared.log("\(#function): \(error)") } nonisolated func workoutSession(_ workoutSession: HKWorkoutSession, didReceiveDataFromRemoteWorkoutSession data: [Data]) { Logger.shared.log("\(#function): \(data.debugDescription)") Task { @MainActor in do { for anElement in data { try handleReceivedData(anElement) } } catch { Logger.shared.log("Failed to handle received data: \(error))") } } } } private func startWorkout() { Task { do { let configuration = HKWorkoutConfiguration() configuration.activityType = .cycling configuration.locationType = .outdoor try await workoutManager.startWorkout(workoutConfiguration: configuration) } catch { Logger.shared.log("Failed to start workout \(error))") } } }
Posted Last updated
.
Post not yet marked as solved
0 Replies
315 Views
Hi, Is there anyway to share a WorkoutScheduler across an iPhone and watch app? If I create a scheduler on the phone app the watch app can't see it and creates its own. I'm using WorkoutScheduler.shared.scheduledWorkouts but end up with two identical sections at the top of the workout app Thanks
Posted
by MJarred.
Last updated
.
Post not yet marked as solved
2 Replies
443 Views
In the wwdc2023-10023 session, we go over how the Apple Watch can be used as a primary workout session manager and the iPhone as the mirrored one. How is it possible to create a workout session on the iPhone and optionally mirror it to the Apple Watch to collect heart rate data? In iOS 17, I still cannot instantiate a HKWorkoutSession, I'm assuming it says it's available because we can have an instance of it as a mirrored copy from the Apple Watch. I find it odd that the iPhone cannot manage the primary session. I hope I'm missing something.
Posted Last updated
.
Post not yet marked as solved
0 Replies
503 Views
I'm experiencing an issue trying to install the 'mirroringworkoutssample' app from the official Apple documentation on my Apple Watch. When attempting a direct installation from the Apple Watch, I receive an error stating, "Cannot install this app due to an inability to verify its integrity." Has anyone else encountered this problem or can provide any solutions or insights? ** I have a 'Development' type certificate that allows for watchOS(it includes iOS, tvOS ..) development. ** also added WKCompanionAppBundleIdentifier com.example.apple-samplecode.MirroringWorkoutsSample7C76V3X7AB.watchkitapp
Posted
by hhajime.
Last updated
.
Post marked as Apple Recommended
663 Views
I am having trouble getting the new mirroring session API to send data to the companion device. when starting a workout on my watch I call startMirroringToCompanionDevice and then go onto my iOS workout manager to handle it via the workoutSessionMirroringStartHandler, I set the delegate here and can confirm that it is indeed not nil within that function but when I go to send some data across I get an error saying the remote session delegate was never set up. I noticed this same behaviour in the WWDC demo and have been unable to find a solution that will allow me to send data across the mirrored session even though I am able to control the workout session state(pause, resume, end) on both Phone and Watch. Has anyone else encountered this issue? Anyone have a solution?
Posted
by sebrob.
Last updated
.
Post not yet marked as solved
1 Replies
504 Views
Hello, I'm trying to understand what's the difference between: HeartRateZoneAlert: static func heartRate(zone: Int) -> Self PowerZoneAlert : static func power(zone: Int) -> Self And also, why HeartRate alerts support range, but Power doesn't support Range?
Posted
by arnaud512.
Last updated
.
Post not yet marked as solved
4 Replies
737 Views
I am unable to see the workout composition from preview in the new WorkoutKit framework. This is reproducible on an iPhone running iOS 17.0 running xcode 15.0 beta 2. I downloaded the Sample Planner app that showcases the new WorkoutKit framework capabilities , introduced in the session 10016 of wwdc 23. I can create workout compositions but the preview presentation doesn’t work as expected. It shows a black screen without any info. I attached a screenshot. You can reproduce it on the sample app when showing the PresentPreviewDemo view.
Posted Last updated
.
Post not yet marked as solved
2 Replies
499 Views
Hi, I have an app that implements the Cycling Power Service 1.1, https://www.bluetooth.com/de/specifications/specs/cycling-power-service-1-1/ As expected, I can select this app as a Health Device in the Bluetooth settings of my Apple Watch. However, when I run the BLE app on the paired iPhone, the Apple Watch does not detect the BLE Service as a Health Device! Is this a bug, or is it designed this way? If so, is there another API where I can send power meter data from iOS to a running Watch Workout?
Posted
by boerni.
Last updated
.
Post not yet marked as solved
1 Replies
405 Views
Dear All, Is there a way to remove a workout? In the tutorial app, it is shown how to schedule workouts. But so far, I haven't seen a way to remove them again, neither from the tutorial app nor from the workouts app on the watch. Many thanks and best regards, Patrick
Posted
by PatDelft.
Last updated
.