【发布时间】:2021-05-24 09:46:37
【问题描述】:
我想在 SwiftUI 中加载以下 GUI:
import SwiftUI
struct ContentView: View {
@ObservedObject var test = Test()
@ObservedObject var healthStore = HealthStore()
func callUpdate() {
print(test.value)
print(healthStore.systolicValue)
print(healthStore.diastolicValue)
}
var body: some View {
Text("Platzhalter")
.padding()
.onAppear(perform: {
healthStore.setUpHealthStore()
callUpdate()
})
Button("Test"){
callUpdate()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
变量 healthStore.systolicValue 和 healthStore.diastolicValue 是通过函数 callUpdate() 调用的。在第一次调用时,两个变量都为零。只有当我通过Test按钮调用该函数时,才会在控制台中输出正确的值。
变量 healthStore.systolicValue 和 healthStore.diastolicValue 在 HealthStore 类中计算:
import Foundation
import HealthKit
class HealthStore: ObservableObject {
var healthStore: HKHealthStore?
var query: HKStatisticsQuery?
public var systolicValue: HKQuantity?
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 {
// This should never fail when using a defined constant.
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 {
// This should never fail when using a defined constant.
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!)
}
}
当我调用 ContentView 时,如何修改我的代码以直接获取 healthStore.systolicValue 和 healthStore.diastolicValue 的正确值?
【问题讨论】: