classHealthService:ObservableObject{lethealthStore:HKHealthStoreletmetsUnit=HKUnit.kilocalorie().unitDivided(by:HKUnit.gramUnit(with:.kilo)).unitDivided(by:HKUnit.hour())init(){self.healthStore=HKHealthStore()letmets=HKQuantityType(.physicalEffort)lethealthTypes:Set=[mets]Task{do{tryawaitself.healthStore.requestAuthorization(toShare:[],read:healthTypes)}catch{print("failed to authorization.")}}}}
funcgetRawMets(date:Date=Date())async->[MetsRawData]{letpyhsicalEffortType=HKQuantityType(.physicalEffort)letstartDay=date.diff(days:0)lettomorrow=date.diff(days:1)// Create the predicate for the queryletpredicate=HKQuery.predicateForSamples(withStart:startDay,end:tomorrow,options:.strictStartDate)returnawaitwithCheckedContinuation{continuationinletquery=HKSampleQuery(sampleType:pyhsicalEffortType,predicate:predicate,limit:HKObjectQueryNoLimit,sortDescriptors:nil){(query,samples,error)inifleterror=error{print("Error: \(error.localizedDescription)")continuation.resume(returning:[])}else{guardletquantitySamples=samplesas?[HKQuantitySample]else{print("No data available")returncontinuation.resume(returning:[])}varret:[MetsRawData]=[]// Process the samplesforsampleinquantitySamples{letmets=sample.quantity.doubleValue(for:self.metsUnit)if(3<mets){letsecond=sample.endDate.timeIntervalSince(sample.startDate)letmethHour=mets*second/3600ret.append(MetsRawData(startDate:sample.startDate,endDate:sample.endDate,mets:methHour))}}continuation.resume(returning:ret)}}// Execute the queryhealthStore.execute(query)}}