@DTS Engineer Thank you for your reply. I now understand the problem I had. I just have another question now. If I want to move all of this code to HealthKitManager class is this the optimal way to do it?
struct WorkoutDetailView: View {
@Environment(HealthKitManager.self) var healthKitManager
let workout: HKWorkout
var body: some View {
ScrollView {
VStack(alignment: .leading) {
//...
}
.task {
do {
workoutLocations = try await healthKitManager.retrieveWorkoutRoute(for: workout)
} catch {
fatalError("error while fetching workout route: \(error)")
}
}
}
}
}
@Observable
class HealthKitManger {
private var healthStore: HKHealthStore?
//...
func retrieveWorkoutRoute(for workout: HKWorkout) async throws -> [CLLocation] {
guard let store = self.healthStore else {
fatalError("retrieveWorkoutRoute(): healthStore is nil. App is in invalid state.")
}
let currentWorkoutPredicate = HKQuery.predicateForObjects(from: workout)
let routeSamplesQuery = HKAnchoredObjectQueryDescriptor(predicates: [.workoutRoute(currentWorkoutPredicate)], anchor: nil)
let queryResults = routeSamplesQuery.results(for: store)
let task = Task {
var workoutRouteLocations: [CLLocation] = []
for try await result in queryResults {
let routeSamples = result.addedSamples
for routeSample in routeSamples {
let routeQueryDescriptor = HKWorkoutRouteQueryDescriptor(routeSample)
let locations = routeQueryDescriptor.results(for: store)
for try await location in locations {
workoutRouteLocations.append(location)
}
}
return workoutRouteLocations
}
return workoutRouteLocations
}
return try await task.value
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: