Get total sleep time for the last 7 days

This commit is contained in:
2024-01-06 14:01:12 +01:00
parent 7557e8c5bf
commit 8e8810493e
2 changed files with 50 additions and 1 deletions

View File

@@ -14,9 +14,24 @@ struct ContentView: View {
Image(systemName: "globe") Image(systemName: "globe")
.imageScale(.large) .imageScale(.large)
.foregroundStyle(.tint) .foregroundStyle(.tint)
Button(action: {
manager.getSleepForLast7Days()
print(manager.sleepForLast7Days)
var seconds = manager.sleepForLast7Days
print("hours: ", seconds / 3600, " minutes: ", (seconds % 3600) / 60, " seconds: ", (seconds % 3600) % 60)
}) {
Text("Hello, world!") Text("Hello, world!")
} }
}
.padding() .padding()
.onAppear {
manager.getSleepForLast7Days()
print(manager.sleepForLast7Days)
var seconds = manager.sleepForLast7Days
print("hours: ", seconds / 3600, " minutes: ", (seconds % 3600) / 60, " seconds: ", (seconds % 3600) % 60)
}
} }
} }

View File

@@ -8,10 +8,18 @@
import Foundation import Foundation
import HealthKit import HealthKit
extension Date {
static var last7Days: Date {
Date().addingTimeInterval(TimeInterval(-60 * 60 * 24 * 7)) // last 7 days
}
}
class HealthKitManager: ObservableObject { class HealthKitManager: ObservableObject {
let healthStore = HKHealthStore() let healthStore = HKHealthStore()
var sleepForLast7Days: Int = 0
init() { init() {
let sleep = HKCategoryType(.sleepAnalysis) let sleep = HKCategoryType(.sleepAnalysis)
@@ -24,7 +32,33 @@ class HealthKitManager: ObservableObject {
print(error) print(error)
} }
} }
self.getSleepForLast7Days()
} }
func getSleepForLast7Days() {
var totalSleep = 0
let sleep = HKCategoryType(.sleepAnalysis)
let sleepPredicate = HKCategoryValueSleepAnalysis.predicateForSamples(equalTo: HKCategoryValueSleepAnalysis.allAsleepValues)
let datePredicate = HKQuery.predicateForSamples(withStart: .last7Days, end: .now)
let predicates = NSCompoundPredicate(andPredicateWithSubpredicates: [sleepPredicate, datePredicate])
let sortByDate = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
let query = HKSampleQuery(
sampleType: sleep,
predicate: predicates,
limit: 100000,
sortDescriptors: [sortByDate])
{_, results, error in
for(_, sample) in results!.enumerated() {
guard let currData:HKCategorySample = sample as? HKCategorySample else { print("There was an error"); return }
let endDate = currData.endDate
let startDate = currData.startDate
let seconds = Int(endDate.timeIntervalSince(startDate))
totalSleep += seconds
}
self.sleepForLast7Days = totalSleep
}
healthStore.execute(query)
}
} }