startMirroringToCompanionDevice(completion:)
Starts mirroring the workout session to the companion iOS device.
Declaration
func startMirroringToCompanionDevice(completion: @escaping @Sendable (Bool, (any Error)?) -> Void)func startMirroringToCompanionDevice() async throwsParameters
- completion:
A block that the system calls when the start request is complete. The system sets the following parameters:
successA Boolean value that indicates whether the system successfully started mirroring the session.
errorIf
successis False, this contains an object that describes the error. Otherwise, it’snil.
Discussion
Call this method in your watchOS app to start a mirrored workout session on the companion iOS app. If your iOS app isn’t running, the system launches it in the background. The iOS companion app must assign a completion handler to its HealthKit Store’s workoutSessionMirroringStartHandler property to process the incoming session.
let configuration = HKWorkoutConfiguration()
configuration.activityType = .running
configuration.locationType = .outdoor
let session: HKWorkoutSession
do {
session = try HKWorkoutSession(healthStore: store,
configuration: configuration)
} catch {
// Handle failure here.
fatalError("*** An error occurred: \(error.localizedDescription) ***")
}
let builder = session.associatedWorkoutBuilder()
let source = HKLiveWorkoutDataSource(healthStore: store,
workoutConfiguration: configuration)
source.enableCollection(for: HKQuantityType(.stepCount), predicate: nil)
builder.dataSource = source
session.delegate = self
builder.delegate = self
self.session = session
self.builder = builder
let start = Date()
// Start the mirrored session on the companion iPhone.
do {
try await session.startMirroringToCompanionDevice()
}
catch {
fatalError("*** Unable to start the mirrored workout: \(error.localizedDescription) ***")
}
// Start the workout session.
session.startActivity(with: start)
do {
try await builder.beginCollection(at: start)
} catch {
fatalError("*** An error occurred while starting the workout: \(error.localizedDescription) ***")
}