I want to get data from apple health on background.. I don't know where to call my function updateOnBackground
I looked on the related topics and I currently have this:
func updateOnBackground() {
let quantityType = HKQuantityType.quantityType(forIdentifier: .heartRate)!
self.healthStore.enableBackgroundDelivery(for: quantityType, frequency: .immediate) { (success, error) in
if let error = error {
print("\(error)")
}
if success {
print("background delivery enabled")
}
}
let query = HKObserverQuery(sampleType: quantityType, predicate: nil) { (query, completionHandler, error) in
self.updateData(){
completionHandler()
}
}
healthStore.execute(query)
}
This is the function for getting the data while the app is active:
class func getMostRecentSample(for sampleType: HKSampleType,
completion: @escaping (HKQuantitySample?, Error?) -> Swift.Void) {
let mostRecentPredicate = HKQuery.predicateForSamples(withStart: Date.distantPast, end: Date(), options: .strictEndDate)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
let limit = 1
let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor]) { (query, samples, error) in
DispatchQueue.main.async {
guard let samples = samples,
let mostRecentSample = samples.first as? HKQuantitySample else {
completion(nil, error)
return
}
//print(samples)
completion(mostRecentSample, nil)
}
}
HKHealthStore().execute(sampleQuery)
}
func updateData(completionHandler: @escaping () -> Void) {
let sampleType = HKQuantityType.quantityType(forIdentifier: .heartRate)!
HealthData.getMostRecentSample(for: sampleType) { (sample, error) in
self.handleNewData(new: sample!)
completionHandler()
}
}
func handleNewData(new: HKQuantitySample) {
print(new)
}
I think function getMostRecentSample here is not needed, how else could i have done this better?