Looking to run the iOS app on Simulator? Start here: README.md.
The main entry point for the BetterFit library.
public class BetterFitplanManager: PlanManager- Manages training planstemplateManager: TemplateManager- Manages workout templatesequipmentSwapManager: EquipmentSwapManager- Handles equipment swapsbodyMapManager: BodyMapManager- Tracks recovery statussocialManager: SocialManager- Manages social featuresnotificationManager: SmartNotificationManager- Handles notificationsautoTrackingService: AutoTrackingService- Processes Watch sensor dataaiAdaptationService: AIAdaptationService- AI-powered plan adaptationimageService: EquipmentImageService- Equipment image management
public func startWorkout(_ workout: Workout)Starts a workout and enables auto-tracking.
public func completeWorkout(_ workout: Workout)Completes a workout, updating history, recovery, streaks, and AI analysis.
public func getWorkoutHistory() -> [Workout]Returns all completed workouts.
public func getRecommendedWorkout() -> Workout?Creates the first planned workout using generated equipment alternatives.
public func getRecommendedWorkout(from catalogue: [Exercise]) -> Workout?Creates the first scheduled template in the active plan's current week. For each entry requiring unavailable equipment, uses the first eligible catalogue exercise with available alternative equipment and the same non-empty set of muscle groups. Repeated entries are swapped individually. Catalogue order determines preference; recovery does not rank the results. Supply exercises appropriate for the workout, as matching muscles alone does not establish movement equivalence.
The result preserves catalogue exercise IDs and metadata, template identity, workout order and target sets. Stored plans and templates stay unchanged. Entries without an eligible alternative retain their original exercise, which may still require unavailable equipment. Returns nil if the first scheduled template cannot be resolved. The no-argument overload continues to use generated alternatives.
public func processMotionData(_ data: MotionData) -> TrackingEvent?Processes Apple Watch motion data for auto-tracking.
public func getTrackingStatus() -> TrackingStatusReturns the current auto-tracking status.
HealthExportParser.parseExport(data:) and parseExport(xml:) return a
HealthExport containing workouts, records, and activitySummaries.
The parser uses Foundation and does not require HealthKit or UI frameworks.
Each HealthActivitySummary preserves the exported dateComponents day
string (yyyy-MM-dd), active energy and goal with their original unit,
exercise time and goal in minutes, and stand hours and goal. Missing or
invalid numeric attributes are nil; measured zero remains zero.
activeEnergyKilocalories and activeEnergyGoalKilocalories convert kcal,
kJ, and J to kilocalories, returning nil for missing or unsupported units.
Activity summaries remain separate from dailySummaries(calendar:), which
aggregates records. Adding the two energy totals would count the same
activity twice. Older encoded exports without activitySummaries decode
with an empty collection.
[HealthActivitySummary] supports csvString(), jsonData(), writeCSV(to:)
and writeJSON(to:). Exports preserve array order and duplicate days. CSV
columns are date, active_energy_kcal, active_energy_goal_kcal,
exercise_minutes, exercise_goal_minutes, stand_hours and stand_goal_hours.
The date stays as the exported calendar day, without time zone conversion.
Missing values and energy with unsupported units are empty CSV fields;
measured zero remains zero. Text containing commas, quotes or line breaks is
quoted, with embedded quotes doubled. Empty CSV exports contain the header
and a newline.
JSON retains the original energy values and unit, uses sorted keys and
omits missing fields. Decode it with a standard JSONDecoder to restore the
same summaries. Empty JSON exports contain an empty array. jsonData() throws
on encoding errors, including non-finite numbers. File writers atomically
create or replace their destination and propagate encoding or file errors;
the parent directory must already exist.
let export = try HealthExportParser.parseExport(data: xmlData)
try export.activitySummaries.writeCSV(to: csvURL)
try export.activitySummaries.writeJSON(to: jsonURL)
let restored = try JSONDecoder().decode(
[HealthActivitySummary].self, from: export.activitySummaries.jsonData())HealthExportParser.parseWorkouts(xml:) and parseWorkouts(data:) return
[ParsedWorkout]. This array supports csvString(), jsonData(),
writeCSV(to:) and writeJSON(to:) for per-workout summaries.
Both formats keep input order and include undated workouts. They use the existing summary properties, which prefer supported child statistics and fall back to workout totals for active energy and distance. Missing metrics become CSV blanks or omitted JSON fields, while measured zero remains zero. Dates use UTC ISO 8601. CSV text containing commas, quotes or line breaks is quoted and escaped.
| CSV column | JSON key | Unit or meaning |
|---|---|---|
activity_type |
activityType |
Raw workout activity type |
source_name |
sourceName |
Exported source name |
start_date |
startDate |
Workout start |
end_date |
endDate |
Workout end |
duration_seconds |
durationSeconds |
Seconds |
active_energy_kcal |
activeEnergyKilocalories |
Kilocalories |
basal_energy_kcal |
basalEnergyKilocalories |
Kilocalories |
distance_metres |
distanceMetres |
Metres |
average_heart_rate_bpm |
averageHeartRateBPM |
Beats per minute |
minimum_heart_rate_bpm |
minimumHeartRateBPM |
Beats per minute |
maximum_heart_rate_bpm |
maximumHeartRateBPM |
Beats per minute |
step_count |
stepCount |
Steps |
JSON is a pretty printed array with sorted keys. These exports contain normalised
summaries; use JSONEncoder on [ParsedWorkout] directly to retain raw child
statistics and full source metadata. File writers replace files atomically and
propagate encoding and file-system errors. Parent directories must already exist.
let workouts = try HealthExportParser.parseWorkouts(data: exportData)
let csv = workouts.csvString()
let json = try workouts.jsonData()
try workouts.writeCSV(to: directory.appendingPathComponent("workouts.csv"))
try workouts.writeJSON(to: directory.appendingPathComponent("workouts.json"))Represents a single exercise.
public struct Exercise: Identifiable, Codable, Equatableid: UUIDname: StringequipmentRequired: EquipmentmuscleGroups: [MuscleGroup]imageURL: String?
Equipment types for exercises.
public enum Equipment: String, Codable, CaseIterablebarbell,dumbbell,kettlebell,machine,cable,bodyweight,bands,other
alternatives() -> [Equipment]- Returns alternative equipment options
Muscle groups targeted by exercises.
public enum MuscleGroup: String, Codable, CaseIterablechest,back,shoulders,biceps,triceps,forearmsabs,obliques,quads,hamstrings,glutes,calves,traps,lats
bodyMapRegion: String- Body map region for recovery tracking
Represents a single set in an exercise.
public struct ExerciseSet: Identifiable, Codable, Equatableid: UUIDreps: Intweight: Double?isCompleted: Booltimestamp: Date?autoTracked: Bool
Represents a workout session.
public struct Workout: Identifiable, Codable, Equatableid: UUIDname: Stringexercises: [WorkoutExercise]date: Dateduration: TimeInterval?isCompleted: BooltemplateId: UUID?
Reusable workout template.
public struct WorkoutTemplate: Identifiable, Codable, Equatableid: UUIDname: Stringdescription: String?exercises: [TemplateExercise]tags: [String]createdDate: DatelastUsedDate: Date?
createWorkout() -> Workout- Converts template to a workout
Training plan for structured programming.
public struct TrainingPlan: Identifiable, Codable, Equatableid: UUIDname: Stringdescription: String?weeks: [TrainingWeek]currentWeek: Intgoal: TrainingGoalcreatedDate: DateaiAdapted: Bool
getCurrentWeek() -> TrainingWeek?advanceWeek()
Training goal types.
public enum TrainingGoal: String, Codable, CaseIterablestrength,hypertrophy,endurance,powerlifting,generalFitness,weightLoss
repRange: ClosedRange<Int>- Recommended rep rangerestTime: TimeInterval- Recommended rest time
Body map for tracking recovery.
public struct BodyMapRecovery: Codable, Equatableregions: [BodyRegion: RecoveryStatus]lastUpdated: Date
recordWorkout(_:at:)- Update each targeted body region once per recorded workout. Multiple muscles or exercises in the same region share one fatigue transition; separate recorded workouts can increase fatigue further. The date defaults to now.updateRecovery(asOf:)- Update based on time elapsed, using the supplied date or now
Recovery status for muscle groups.
public enum RecoveryStatus: String, Codable, Equatablerecovered,slightlyFatigued,fatigued,sore
recommendedRestHours: Double
User profile for social features.
public struct UserProfile: Identifiable, Codable, Equatableid: UUIDusername: StringcurrentStreak: IntlongestStreak: InttotalWorkouts: IntactiveChallenges: [UUID]
Workout challenge.
public struct Challenge: Identifiable, Codable, Equatableid: UUIDname: Stringdescription: Stringgoal: ChallengeGoalstartDate: DateendDate: Dateparticipants: [UUID]progress: [UUID: Double]
Challenge goal types.
public enum ChallengeGoal: Codable, EquatableworkoutCount(target: Int)totalVolume(target: Double)consecutiveDays(target: Int)specificExercise(exerciseId: UUID, target: Int)
Manages training plans.
public class PlanManagergetActivePlan() -> TrainingPlan?setActivePlan(_:)addPlan(_:)updatePlan(_:)removePlan(_:)getAllPlans() -> [TrainingPlan]
Manages workout templates.
public class TemplateManagergetAllTemplates() -> [WorkoutTemplate]getTemplate(id:) -> WorkoutTemplate?addTemplate(_:)updateTemplate(_:)deleteTemplate(id:)searchByTag(_:) -> [WorkoutTemplate]searchByName(_:) -> [WorkoutTemplate]getRecentTemplates(limit:) -> [WorkoutTemplate]createWorkout(from:) -> Workout?createTemplate(from:name:tags:) -> WorkoutTemplate
Manages equipment swaps.
public class EquipmentSwapManagersetAvailableEquipment(_:)isAvailable(_:) -> BoolfindAlternatives(for:) -> [Exercise]findAlternatives(for:from:) -> [Exercise]- Select real alternatives from a supplied exercise cataloguesuggestSwaps(for:) -> [(original: Exercise, alternatives: [Exercise])]suggestSwaps(for:from:) -> [(original: Exercise, alternatives: [Exercise])]- Select catalogue alternatives for a workoutsuggestEntrySwaps(for:from:) -> [WorkoutSwapSuggestion]- Select catalogue alternatives with workout entry IDsapplySwap(workout:originalExerciseId:newExercise:) -> BoolapplySwap(workout:workoutExerciseId:newExercise:) -> Bool- Replace a specific workout entry
findAlternatives(for:from:) returns catalogue exercises only when the original
equipment is unavailable. Candidates must use available equipment listed by
Equipment.alternatives() and have exactly the same non-empty set of muscle
groups. Muscle ordering and repeated groups do not affect matching. The original
exercise ID is excluded, and the first eligible entry for each candidate ID is
returned in catalogue order with its name, ID and image unchanged.
let swaps = EquipmentSwapManager(availableEquipment: [.dumbbell, .machine])
let alternatives = swaps.findAlternatives(for: barbellPress, from: exerciseCatalogue)
let suggestions = swaps.suggestSwaps(for: workout, from: exerciseCatalogue)suggestSwaps(for:from:) applies those matching rules to every workout entry.
Suggestions follow workout order, and alternatives retain catalogue order and
metadata. Entries with available equipment or no eligible alternative are omitted.
Repeated workout entries remain separate suggestions. Neither the workout nor
its sets are changed until the caller applies a selected swap with applySwap.
suggestEntrySwaps(for:from:) returns a WorkoutSwapSuggestion for each eligible
entry, with workoutExerciseId, original and alternatives. It uses the same
catalogue matching rules and preserves workout order, including separate results
for repeated exercise definitions. Available equipment and entries without an
eligible alternative are omitted. The workout is unchanged.
Pass the suggestion's entry ID to apply a selected alternative to that occurrence. The ID continues to target the same entry if the workout is reordered.
if let suggestion = swaps.suggestEntrySwaps(for: workout, from: exerciseCatalogue).last,
let replacement = suggestion.alternatives.first {
swaps.applySwap(
workout: &workout, workoutExerciseId: suggestion.workoutExerciseId, newExercise: replacement)
}Suggestions are snapshots. Regenerate them after editing a workout or changing available equipment; applying a swap does not revalidate a suggestion.
Use applySwap(workout:workoutExerciseId:newExercise:) with a WorkoutExercise.id
to replace one occurrence of a repeated exercise. It changes only that entry's
exercise, preserving its ID, sets and notes and all other workout data. It returns
false without mutation if the entry is missing. The existing originalExerciseId
overload continues to replace the first entry matching an Exercise.id.
if let entry = workout.exercises.last,
let replacement = swaps.findAlternatives(for: entry.exercise, from: exerciseCatalogue).first {
swaps.applySwap(workout: &workout, workoutExerciseId: entry.id, newExercise: replacement)
}Both application methods use the caller's selected exercise without validating equipment availability or muscle matching. Choose an eligible replacement before applying it; sets and loads are preserved without adjustment.
Muscle matching does not establish movement equivalence. Supply a catalogue
appropriate for the workout. This opt-in lookup does not change the generated
alternatives returned by findAlternatives(for:) or suggestSwaps(for:).
Manages body map recovery.
public class BodyMapManagergetRecoveryMap() -> BodyMapRecoveryrecordWorkout(_:)getRecoveryStatus(for:) -> RecoveryStatusisReadyForTraining(region:) -> BoolgetRecommendedExercises(available:avoidSoreRegions:) -> [Exercise]getOverallRecoveryPercentage() -> Doublereset()
Read methods derive a current snapshot from the stored recovery baseline. Reading the map, a region status, training readiness, recommendations or overall recovery does not restart the recovery clock. Hourly polling produces the same status as one read at the end of the same elapsed period, using the existing fatigue thresholds. Returned maps are independent value snapshots.
recordWorkout(_:) refreshes elapsed recovery before applying fatigue and starts
a new baseline at the recording time. reset() discards the baseline. The
initializer accepts now: () -> Date for deterministic reads, recording and reset;
it defaults to the system clock.
Recovery still uses one shared timestamp for all regions. This API does not add
per-region workout timestamps or restore recovery through the facade's startup
loading. Direct BodyMapRecovery.updateRecovery(asOf:) calls mutate that value;
use manager reads when polling without consuming the baseline.
Manages social features.
public class SocialManagerrecordWorkout(date:)getCurrentStreak() -> IntgetLongestStreak() -> IntgetAllChallenges() -> [Challenge]getActiveChallenges() -> [Challenge]joinChallenge(_:) -> BoolleaveChallenge(_:) -> BoolcreateChallenge(_:)updateChallengeProgress(challengeId:userId:progress:) -> BoolgetChallengeLeaderboard(challengeId:) -> [(userId: UUID, progress: Double)]checkChallengeCompletion(challengeId:userId:) -> BoolgetUserProfile() -> UserProfileupdateUserProfile(_:)
Manages smart notifications.
public class SmartNotificationManagerscheduleNotifications(userProfile:workoutHistory:activePlan:)getScheduledNotifications() -> [SmartNotification]cancelNotification(id:)cancelAllNotifications()
HealthExportParser.parseExport(xml:) reads Apple Health export XML without
requiring HealthKit. Call dailySummaries(calendar:) on the result to aggregate
records by their start date in the supplied calendar.
DailyHealthSummary.sleepDuration reports seconds asleep for legacy asleep,
unspecified, core, deep and REM categories, including their numeric HealthKit
values. Overlapping asleep intervals count once, including duplicates from
different sources. Awake, in-bed, unknown categories and incomplete or
non-positive intervals are excluded. A day without valid asleep intervals has
nil sleep duration, which remains an empty field in CSV and is omitted in JSON.
Apple documents the sleep categories and overlapping samples in
HKCategoryValueSleepAnalysis.
Intervals crossing midnight remain entirely on their start day. The summary does not prioritise sources or subtract awake samples that conflict with asleep samples. CSV and JSON exports use the same corrected duration.
Auto-tracking service for Watch sensors.
public class AutoTrackingServicestartTracking(workout:)stopTracking()processMotionData(_:) -> TrackingEvent?completeCurrentSet() -> ExerciseSet?nextExercise()getTrackingStatus() -> TrackingStatus
Motion data from Watch sensors.
public struct MotionDataacceleration: [Double]rotation: [Double]heartRate: Double?timestamp: Date
public init(
acceleration: [Double],
rotation: [Double],
heartRate: Double? = nil,
timestamp: Date = Date()
)isRepetitionDetected() -> BoolisRestPeriod() -> Bool
Tracking events from auto-tracking.
public enum TrackingEventrepDetected(count: Int)setCompleted(reps: Int)exerciseCompleted
Current auto-tracking status.
public struct TrackingStatusisTracking: BoolcurrentExercise: IntdetectedReps: Int
AI service for adaptive training.
public class AIAdaptationServiceanalyzePerformance(workouts:currentPlan:) -> [Adaptation]applyAdaptations(_:to:)
Training plan adaptation suggestions.
public enum Adaptation: EquatablereduceVolume(percentage: Int)increaseVolume(percentage: Int)adjustIntensity(change: Int)deloadWeek
Service for equipment images.
public class EquipmentImageServicegetImage(for: Equipment) -> EquipmentImage?getImage(for: Exercise) -> EquipmentImage?cacheImage(_:for:)getAllImages() -> [EquipmentImage]loadCustomImage(url:for:) async throws -> EquipmentImagegenerateAIImage(for:style:) async throws -> EquipmentImage
Equipment image model.
public struct EquipmentImage: Identifiable, Equatableid: UUIDequipmentType: Equipmenturl: Stringis3D: BoolisAIGenerated: Bool
Image generation styles.
public enum ImageStyle: String, CaseIterablerealistic3D,cartoon,schematic,photographic
Parses an Apple Health export (export.xml). Foundation only, so it runs off device and in tests.
public enum HealthExportParserparseWorkouts(data:)/parseWorkouts(xml:)- workouts with child statisticsparseRecords(data:)/parseRecords(xml:)- top-level records (steps, heart rate, energy, distance, body mass, sleep)parseExport(data:)/parseExport(xml:)- both of the above as oneHealthExport
Throws HealthExportParser.ParseError.malformedXML on malformed XML.
A workout from the export, with one WorkoutStatistics per quantity type nested under it. ParsedWorkout exposes per-workout summaries: activeEnergyKilocalories, basalEnergyKilocalories, distanceMetres, averageHeartRate, minimumHeartRate, maximumHeartRate, and stepCount. Statistics win over the totals written on the workout element, and unknown statistic types are kept as .other(type).
The XML parser treats negative, non-finite (NaN or infinity), empty and malformed numeric workout measurements as missing. This applies to workout duration, energy and distance totals, and each statistic's sum, average, minimum and maximum independently. The workout and statistic metadata remain available. Valid zero values are retained, and missing child measurements still fall back to valid workout totals. This validation applies when parsing XML; models constructed or mutated directly do not validate their numeric properties.
A top-level record from the export. Quantity records carry a numeric value. Category records, such as sleep analysis, carry categoryValue as a string instead. Normalised helpers: valueKilocalories, valueMetres, valueKilograms, and duration from the start and end dates. Unknown record types are kept as .other(type).
HealthExport holds workouts and records together, with records(of:) to filter records by kind.
Record conversion helpers accept energy in kcal, cal, kJ or J, distance in m, km or mi, and body mass in kg, g or lb, without regard to case. Omitted units retain the defaults of kcal, metres and kilograms. Empty or unsupported units return nil from the conversion helpers while preserving the raw value and unit. Daily summaries skip those unsupported measurements, including a later body mass sample with an unsupported unit. Days containing only unsupported measurements retain missing metrics, exported as empty CSV fields and omitted JSON properties. Measured zero remains zero.
HealthExport.weeklyTrainingSummaries(calendar:) groups workouts by their start
date into calendar weeks and returns summaries in date order. Workouts without
a start date are skipped. Pass an explicit calendar to control the time zone
and first day of the week.
[WeeklyTrainingSummary] supports csvString(), jsonData(), writeCSV(to:)
and writeJSON(to:). All four methods throw on encoding or file errors. Exports
preserve array order and use ISO8601 dates. File writes atomically create or
replace the destination, whose parent directory must already exist.
CSV columns are week_start, workout_count, duration_seconds,
active_energy_kcal, distance_metres, average_heart_rate,
maximum_heart_rate and activity_counts. Heart rates are in beats per minute;
the average is the unweighted mean of per-workout averages. Missing metrics
are empty CSV fields and omitted JSON properties; measured zero stays zero.
Activity counts use a JSON object with sorted keys inside a quoted CSV field,
so activity names containing commas or quotes are preserved. Empty CSV exports
contain only the header and a newline; empty JSON exports contain an empty array.
let export = try HealthExportParser.parseExport(data: xmlData)
let weeks = export.weeklyTrainingSummaries(calendar: calendar)
try weeks.writeCSV(to: csvURL)
try weeks.writeJSON(to: jsonURL)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let restored = try decoder.decode([WeeklyTrainingSummary].self, from: weeks.jsonData())