Created
December 4, 2024 12:41
-
-
Save shawn-frank/48adf6bf1d2141878ff971c4fae1038d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// SwiftUI-HealtKit-Sample | |
// | |
// Created by Shawn Frank on 30/11/2024. | |
// | |
import SwiftUI | |
import HealthKit | |
struct ContentView: View { | |
@StateObject private var stepCounter = StepCounter() | |
var body: some View { | |
VStack { | |
Text("Steps Today") | |
.font(.title) | |
.padding() | |
if let steps = stepCounter.steps { | |
Text("\(steps)") | |
.font(.largeTitle) | |
.bold() | |
.padding() | |
} else { | |
Text("Loading...") | |
.font(.headline) | |
.padding() | |
} | |
} | |
.onAppear { | |
stepCounter.requestAuthorization() | |
} | |
} | |
} | |
class StepCounter: ObservableObject { | |
private var healthStore = HKHealthStore() | |
@Published var steps: Int? | |
func requestAuthorization() { | |
// Check if HealthKit is available | |
guard HKHealthStore.isHealthDataAvailable() else { | |
print("HealthKit is not available on this device.") | |
return | |
} | |
let stepType = HKQuantityType.quantityType(forIdentifier: .stepCount)! | |
healthStore.requestAuthorization(toShare: [], read: [stepType]) { success, error in | |
if success { | |
self.fetchSteps() | |
} else if let error = error { | |
print("Authorization failed: \(error.localizedDescription)") | |
} | |
} | |
} | |
func fetchSteps() { | |
let stepType = HKQuantityType.quantityType(forIdentifier: .stepCount)! | |
let startOfDay = Calendar.current.startOfDay(for: Date()) | |
let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: Date(), options: .strictStartDate) | |
let query = HKStatisticsQuery(quantityType: stepType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, error in | |
guard let result = result, let sum = result.sumQuantity() else { | |
print("Failed to fetch steps: \(String(describing: error?.localizedDescription))") | |
DispatchQueue.main.async { | |
self.steps = nil | |
} | |
return | |
} | |
let stepCount = Int(sum.doubleValue(for: HKUnit.count())) | |
DispatchQueue.main.async { | |
self.steps = stepCount | |
} | |
} | |
healthStore.execute(query) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment