You need to enable JavaScript to run this app. SwiftUI调用HealthKit时ContentView首次加载无法获取血压值的问题
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI调用HealthKit时ContentView首次加载无法获取血压值的问题

问题根因

  1. HealthStore作为ObservableObject,其中的systolicValue、diastolicValue属性未添加@Published注解,值更新时不会主动通知视图刷新。
  2. HealthKit的授权申请、数据查询均为异步操作,onAppear中调用完setUpHealthStore()后立刻执行callUpdate()时,异步操作还未返回结果,自然读取到nil值。

修改方案

1. 调整HealthStore类

给两个数值属性添加@Published注解,值变更时会自动触发视图更新:

import Foundation
import HealthKit

class HealthStore: ObservableObject {
    var healthStore: HKHealthStore?
    var query: HKStatisticsQuery?
    
    // 新增@Published注解
    @Published public var systolicValue: HKQuantity?
    @Published public var diastolicValue: HKQuantity?

    init() {
        if HKHealthStore.isHealthDataAvailable() {
            healthStore = HKHealthStore()
        }
    }

    func setUpHealthStore() {
        let typesToRead: Set = [
            HKQuantityType.quantityType(forIdentifier: .bloodPressureSystolic)!,
            HKQuantityType.quantityType(forIdentifier: .bloodPressureDiastolic)!
        ]

        healthStore?.requestAuthorization(toShare: nil, read: typesToRead, completion: { success, error in
            if success {
                print("requestAuthrization")
                self.calculateBloodPressureSystolic()
                self.calculateBloodPressureDiastolic()
            }
        })
    }

    func calculateBloodPressureSystolic() {
        guard let bloodPressureSystolic = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic) else {
            fatalError("*** Unable to get the bloodPressure count ***")
        }
        query = HKStatisticsQuery(quantityType: bloodPressureSystolic,
                                  quantitySamplePredicate: nil,
                                  options: .discreteAverage) {
            query, statistics, error in
            DispatchQueue.main.async{
                self.systolicValue = statistics?.averageQuantity()
            }
        }
        healthStore!.execute(query!)
    }
    
    func calculateBloodPressureDiastolic() {
        guard let bloodPressureDiastolic = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic) else {
            fatalError("*** Unable to get the bloodPressure count ***")
        }
        query = HKStatisticsQuery(quantityType: bloodPressureDiastolic,
                                  quantitySamplePredicate: nil,
                                  options: .discreteAverage) {
            query, statistics, error in
            DispatchQueue.main.async{
                self.diastolicValue = statistics?.averageQuantity()
            }
        }
        healthStore!.execute(query!)
    }
}

2. 调整ContentView

  • 把@ObservedObject替换为@StateObject(iOS14+支持),避免视图刷新时HealthStore实例被重复创建
  • 取消onAppear中同步调用callUpdate()的逻辑,改为监听两个数值属性的变化,两个值都加载完成后自动执行对应逻辑
import SwiftUI

struct ContentView: View {
    @ObservedObject var test = Test()
    // 替换为@StateObject避免实例重复初始化,iOS13以下可将实例放到View外部传入
    @StateObject var healthStore = HealthStore()
    
    func callUpdate() {
        print(test.value)
        print(healthStore.systolicValue ?? "无收缩压数据")
        print(healthStore.diastolicValue ?? "无舒张压数据")
    }
    
    var body: some View {
        VStack {
            Text("Platzhalter")
                .padding()
                .onAppear(perform: {
                    healthStore.setUpHealthStore()
                })
                // 监听两个值的变化,都不为nil时执行callUpdate
                .onChange(of: healthStore.systolicValue) { _ in
                    guard let _ = healthStore.systolicValue, let _ = healthStore.diastolicValue else { return }
                    callUpdate()
                }
                .onChange(of: healthStore.diastolicValue) { _ in
                    guard let _ = healthStore.systolicValue, let _ = healthStore.diastolicValue else { return }
                    callUpdate()
                }
            
            Button("Test"){
                callUpdate()
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

内容的提问来源于stack exchange,提问作者Jorge Reich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 17:45:03