Hello :)
I'm trying to make Apple Watch app that can detect hand wash is finished. I followed workout app that apple provided, and succeed in getting hand wash count information .
but how can I detect hand wash event when app is not foreground or executed.
my full code is as below
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
The start view.
*/
import SwiftUI
import HealthKit
var healthStore: HKHealthStore!
struct StartView: View {
@State var count: Int = 0
//
// ContentView.swift
// handwash
//
// Created by pedro jung on 2022/06/09.
//
var body: some View {
Button(action: {
checkHealthKit()
}, label: {
Text("Button\(self.count)")
})
}
func checkHealthKit() {
print(count)
healthStore = HKHealthStore()
let healthTypes = Set([
HKCategoryType.categoryType(forIdentifier: .handwashingEvent)!
])
healthStore.requestAuthorization(toShare: nil, read: healthTypes)
{ (success, error) in
fetchHandWashing()
}
}
func fetchHandWashing() {
let now = Date()
let calendar = Calendar.current
let yesterday = calendar.date(byAdding: .day, value: -1, to: calendar.startOfDay(for: now))
let predicate = HKQuery.predicateForSamples(withStart: yesterday, end: now, options: [])
let sortDescriptor = [NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true)]
let washingEvent = HKCategoryType.categoryType(forIdentifier: .handwashingEvent)!
let query = HKSampleQuery(sampleType: washingEvent,
predicate: predicate,
limit: HKObjectQueryNoLimit,
sortDescriptors: sortDescriptor) {
(query, results, error) in
guard error == nil else { print("error"); return }
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd HH:mm:ss"
format.timeZone = TimeZone(identifier: "Asia/Tokyo")
print("\(format.string(from: yesterday!)) - \(format.string(from: now)) r \(results)esult 🥳:")
if let tmpResults = results as? [HKCategorySample] {
print(tmpResults.count)
self.count=tmpResults.count
tmpResults.forEach { (sample) in
print(sample)
}
}
}
healthStore.execute(query)
healthStore.enableBackgroundDelivery(
for: washingEvent,
frequency: .immediate,
withCompletion: { succeeded, error in
guard error != nil && succeeded else {
self.count = self.count+1
//send information!
return
}
// Background delivery is enabled
}
)
let query2 = HKObserverQuery(
sampleType: washingEvent,
predicate: nil,
updateHandler: { query, completionHandler, error in
defer {
completionHandler()
}
guard error != nil else {
return
}
// TODO
})
healthStore.execute(query2)
}
}