How do I display a string in View in Swift from HKSampleQuery

Viewed 11

since this is my first Swift project and I am new to programming in general. I need some help with extracting the sample data I fetched from the query and printing it in the console. I am looking for a way to extract latestHr from the local scope and display it in the View in the app itself which is in the scope below:

var body: some View {

    return VStack {

    }

but I couldn't find a way to do it correctly. This is most of the code I am using and the parts for calculation and fetching.

    func latestheartRate(){
        guard let sampleType = HKObjectType.quantityType(forIdentifier: .heartRate) else{return}
        let startDate = Calendar.current.date(byAdding: .month, value: -1, to: Date())
        
        let predicate = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: .strictEndDate)
        
        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
        
        
    
        let query = HKSampleQuery(sampleType: sampleType, predicate: predicate, limit: Int(HKObjectQueryNoLimit), sortDescriptors: [sortDescriptor]) {(sample, result, error) in guard error == nil else {
            return
        }
            let data = result![0] as! HKQuantitySample
            let unit = HKUnit(from:"count/min")
            let latestHr = data.quantity.doubleValue(for: unit)
            let date = DateFormatter()
            date.dateFormat = "HH:mm E, d MMM y"
            let StartDate = date.string(from: data.startDate)
            let EndDate = date.string(from: data.endDate)
            print("Latest Hr\(latestHr) BPM // StartDate \(StartDate): EndDate \(EndDate)")
            
            let HR = String(latestHr)
            
           
        }
        
        healthStore.execute(query)
        
        
        

    }
    
        
    //trigger the function to authorize read and write heart rate
    init()
    {
        authorizeHealthKit()

    }
    var body: some View {
        
        return VStack {
            
        }
0 Answers
Related