SwiftUI Healthkit 血压查询

Posted

技术标签:

【中文标题】SwiftUI Healthkit 血压查询【英文标题】:SwiftUI Health kit blood Presure query 【发布时间】:2020-07-20 15:12:56 【问题描述】:

我正在尝试制作一个应用程序来读取健康套件中的血压。

就行了 - self.dataX.bloodPresureDetails.append(sysPresData) (第一块倒数第三行) 我收到这个错误

线程 2:致命错误:没有 UserHealthDetails 类型的 ObservableObject 成立。 UserHealthDetails 的 View.environmentObject(_:) 可能是 作为这种观点的祖先失踪了。

HalthStore 文件

class HealthStore 
@EnvironmentObject var dataX: UserHealthDetails
var healthStore: HKHealthStore?
var sampleQuery: HKSampleQuery?

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


func requestAutherisation(completion: @escaping (Bool) -> Void) 
    
    let presSystolic = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)!
    let presDiastolic = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)!
    let heartRate = HKObjectType.quantityType(forIdentifier: .heartRate)!

    guard let healthStore = self.healthStore else  return completion(false) 
 
    healthStore.requestAuthorization(toShare: [], read: [presSystolic, presDiastolic, heartRate])  (sucsess, error) in
        completion(sucsess)
    



 func readSampleByBloodPressure()
     
            guard let bloodtype = HKQuantityType.correlationType(forIdentifier: HKCorrelationTypeIdentifier.bloodPressure),
           let systolicType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodPressureSystolic),
           let diastolicType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodPressureDiastolic) else 

               return
       

      let startDate = Calendar.current.date(byAdding: .day, value: -7, to: Date())!
     let endDate = Date()
     let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: true)
    let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)
      sampleQuery = HKSampleQuery(sampleType: bloodtype, predicate: predicate, limit: 0, sortDescriptors: [sortDescriptor])
          (sampleQuery, results, error ) -> Void in

            if let dataList = results as? [HKCorrelation] 

             for data in dataList
             
                 if let data1 = data.objects(for: systolicType).first as? HKQuantitySample,
                     let data2 = data.objects(for: diastolicType).first as? HKQuantitySample 

                     let sysPvalue = data1.quantity.doubleValue(for: HKUnit.millimeterOfMercury())
                     let diaPvalue = data2.quantity.doubleValue(for: HKUnit.millimeterOfMercury())

                    let sysPresData = UserHealthDetails.BloodPresure(diaPres: diaPvalue, sysPres: sysPvalue, date: startDate)
                    
                    self.dataX.bloodPresureDetails.append(sysPresData)
                 
             

     

 
 
 
if let healthStore = healthStore,
let sampleQuery = self.sampleQuery  healthStore.execute(sampleQuery) 


 

内容视图

struct ContentView: View 

private var healthStore: HealthStore?
@EnvironmentObject var dataX: UserHealthDetails

init () 
    healthStore = HealthStore()


static let dateFormat: DateFormatter = 
       let formatter = DateFormatter()
       formatter.dateStyle = .long
       return formatter
   ()

var body: some View 
    HStack 
        List
            ForEach(dataX.bloodPresureDetails, id: \.self)  data in
                Text("\(data.diaPres)")
                
            
        
       
    
   
    
    
        .onAppear 
            if let healthStore = self.healthStore 
                healthStore.requestAutherisation  sucsess in
                    if sucsess 
                        healthStore.readSampleByBloodPressure()
                        print("readSampleByBloodPressure")
                        
                    
                
            
    
    

class UserHealthDetails: ObservableObject 

@Published var bloodPresureDetails: [BloodPresure] = []


struct BloodPresure: Identifiable, Hashable 
    let id = UUID()
    let diaPres: Double
    let sysPres: Double
    let date: Date

【问题讨论】:

【参考方案1】:

@EnvironmentObject 变量是从环境中获取的,这意味着超级视图需要在任何View 类型上使用.environmentObject(_:) 函数来提供它们。您似乎没有这样做,因此您的 ContentView 在尝试访问您定义的 @EnvironmentObject var 时会崩溃。

Here's a link on how you should fix this problem


作为旁注,您的 HealthStore 课程有这一行:

@EnvironmentObject var dataX: UserHealthDetails

你似乎没有使用它(我认为你不应该在 Views 之外使用 @EnvironmentObject),所以你可能想要删除它。

【讨论】:

以上是关于SwiftUI Healthkit 血压查询的主要内容,如果未能解决你的问题,请参考以下文章

HealthKit 读取数据心率和血压“同步后的最新更新”

HealthKit 读取数据心率和血压“同步后的最新更新”

从 HealthKit 查询更新 SwiftUI

从 HealthKit 查询更新 SwiftUI

WatchOS 上的 HealthKit 查询是不是受限?

SwiftUI - HealthKit 中的 DispatchQueue.main.async