Post

Replies

Boosts

Views

Activity

Reply to Determining crash on HKObject _validateForCreation
Since I needed some time to figure the implementation out, here is a code example from my workout app "Progression" on how to handle the duration limits: private func createAndStoreHealthKitWorkout(start: Date, end: Date, workoutName: String) {         let device = HKDevice(name: UIDevice.current.localizedModel,                               manufacturer: Constants.deviceManufacturer,                               model: UIDevice.current.localizedModel,                               hardwareVersion: modelIdentifier(),                               firmwareVersion: nil,                               softwareVersion: UIDevice.current.systemVersion,                               localIdentifier: nil,                               udiDeviceIdentifier: nil) let maximumAllowedWorkoutDuration = 345600.0 let endDate: Date if #available(iOS 13, *) { let timeIntervalAdjustedForMinimumLimit = HKObjectType.workoutType().isMinimumDurationRestricted ? max( end.timeIntervalSince(start), HKObjectType.workoutType().minimumAllowedDuration ) : end.timeIntervalSince(start) let timeIntervalAdjustedForDurationLimits = HKObjectType.workoutType().isMaximumDurationRestricted ? min( timeIntervalAdjustedForMinimumLimit, HKObjectType.workoutType().maximumAllowedDuration ) : timeIntervalAdjustedForMinimumLimit endDate = Date(timeInterval: timeIntervalAdjustedForDurationLimits, since: start) } else { endDate = Date(timeInterval: maximumAllowedWorkoutDuration, since: start) } let workoutEntry = HKWorkout( activityType: .traditionalStrengthTraining, start: start, end: endDate, workoutEvents: nil, totalEnergyBurned: nil, totalDistance: nil, totalSwimmingStrokeCount: nil, device: device, metadata: [Constants.workoutNameMetadataKey: workoutName] )         healthStore?.save(workoutEntry, withCompletion: { (_, _) in }) } Hope I saved someones time. Note that the hardcoded "maximumAllowedWorkoutDuration" (probably not needed for <iOS 13 versions) is the limit for workout object types.
Jun ’21