I figured out that the app im developing not the sample project was causing the HealthKit service to corrupt which subsequently caused the freeze in HKLiveWorkoutBuilder.
Below is the code for how i end and start workouts in my app. I cant figure out why healthkit gets corrupted.
func start() async throws {
guard !sessionState.isActive else { return }
let configuration = HKWorkoutConfiguration()
configuration.activityType = .swimming
configuration.locationType = .outdoor
configuration.swimmingLocationType = .openWater
if extendedSession == nil {
extendedSession = WKExtendedRuntimeSession()
}
session = try HKWorkoutSession(healthStore: store, configuration: configuration)
builder = session?.associatedWorkoutBuilder()
builder?.dataSource = HKLiveWorkoutDataSource(healthStore: store, workoutConfiguration: configuration)
session?.delegate = self
builder?.delegate = self
print("💧 Submersion Manager: \(manager == nil ? "Unavalible" : "Running")")
//session?.startActivity(with: .now)
try await withTimeout(for: .seconds(10)) {
try await self.builder?.beginCollection(at: .now)
}
session?.startActivity(with: .now)
if extendedSession?.state != .running {
extendedSession?.start()
}
await addMetadata()
}
func end() async {
self.logger.info("Stopping...")
self.sessionState = .stopped
session?.stopActivity(with: .now)
do {
if let temp = weatherManager.airTemperature?.value {
try await self.builder?.addMetadata([
HKMetadataKeyWeatherTemperature: HKQuantity(
unit: HKUnit.degreeCelsius(),
doubleValue: temp
)
])
}
self.logger.info("Ending...")
session?.end()
try await self.builder?.endCollection(at: .now)
let wk = try await self.builder?.finishWorkout()
self.logger.info("Showing Summary")
await MainActor.run{
self.sessionState = .ended
self.dip = wk
}
self.logger.info("✅ Workout saved successfully")
} catch {
self.logger.error("❌ Failed to save workout: \(error.localizedDescription)")
await MainActor.run {
self.error = DipError.workoutError("Failed to save workout")
self.showError = true
}
}
}
func reset() {
// Clean up sessions before resetting state
if let extendedSession = extendedSession, extendedSession.state == .running {
extendedSession.invalidate()
}
extendedSession = nil
session = nil
builder = nil
dip = nil
sessionState = .notStarted
elapsedTime = 0
CMWaterTemp = nil
hr = 0.0
autoDuration = nil
submersionState = .unknown
submergedDate = nil
print("Reset")
WidgetCenter.shared.reloadAllTimelines()
}
Topic:
App & System Services
SubTopic:
Health & Fitness
Tags: