Class

HKWorkoutRouteBuilder

A builder object that incrementally constructs a workout route.

Overview

Use the HKWorkoutRouteBuilder to create a route and associate it with a workout. First, you must request three types of permission, including authorization to:

To create a workout route, start by creating a new workout route builder:

// Create the route builder.
let routeBuilder = HKWorkoutRouteBuilder(healthStore: store, device: nil)

As your app receives location data, filter the data and call insertRouteData(_:completion:) to add it to the builder. Do not insert any location data whose accuracy is greater than 50 meters. Apps that read the data may also perform additional smoothing before using the data.

// MARK: - CLLocationManagerDelegate Methods.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
    // Filter the raw data.
    let filteredLocations = locations.filter { (location: CLLocation) -> Bool in
        location.horizontalAccuracy <= 50.0
    }
    
    guard !filteredLocations.isEmpty else { return }
    
    // Add the filtered data to the route.
    routeBuilder.insertRouteData(filteredLocations) { (success, error) in
        if !success {
            // Handle any errors here.
        }
    }
}

After the workout is finished, save the workout. Then call finishRoute(with:metadata:completion:) to create the route data and associate it with the workout.

// Create the route, save it, and associate it with the provided workout.
routeBuilder.finishRoute(with: myWorkout, metadata: myMetadata) { (newRoute, error) in
    
    guard newRoute != nil else {
        // Handle any errors here.
        return
    }
    
    // Optional: Do something with the route here.
}

Topics

Creating the Builder

init(healthStore: HKHealthStore, device: HKDevice?)

Creates and returns a new workout route builder.

Relationships

Inherits From

Conforms To

See Also