0

I have created a watch app with live heart rate record, for that i have used the workout session and HKAnchoredObjectQuery to fetch the results. In this apple has mentioned that, every 5 seconds will update the heart rate value, but in my case it will take upto 5-10 sec to update. I am using watch serious 3 and i need to collect the value for exactly every 5 seconds.

func startWorkout() {
    if (session != nil) {
        return
    }
    let workoutConfiguration = HKWorkoutConfiguration()
    workoutConfiguration.activityType = .walking
    workoutConfiguration.locationType = .outdoor
    do {
        session = try HKWorkoutSession(healthStore: healthStore, configuration: workoutConfiguration)
        session?.delegate = self
    } catch {
        print("Unable to create the workout session!")
    }
    session?.startActivity(with: Date())
}
func startHeartRateStreamingQuery(_ workoutStartDate: Date){
    
    guard let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else { return nil }
    
    let datePredicate = HKQuery.predicateForSamples(withStart: workoutStartDate, end: nil, options: .strictEndDate )
    let predicate = NSCompoundPredicate(andPredicateWithSubpredicates:[datePredicate])
    
    let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: predicate, anchor: nil, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
        self.updateHeartRate(sampleObjects)
    }
    
    heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in
        self.updateHeartRate(samples)
    }
    healthStore.execute(heartRateQuery)
}
func updateHeartRate(_ samples: [HKSample]?) {
         guard let heartRateSamples = samples as? [HKQuantitySample] else {return}
       for sample in heartRateSamples {
         let timeStamp = sample.startDate
         let value = sample.quantity
         print("\(timeStamp)_\(value)")
     }
}
Ahmet Sina Ustem
  • 1,090
  • 15
  • 32
Velu
  • 21
  • 3

0 Answers0