totalnoobJP
totalnoobJP

Reputation: 19

SwiftUI: Reading visionPrescription from HealthKit

My goal: reading contact lens prescription from HealthKit and being able to use specific values, e.g. cylinder.

But no matter my approach, I run into authorization issues and have not been able to successfully read the data.

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Authorization to read the following types is disallowed: HKVisionPrescriptionTypeIdentifier

Here is my current code:

private func requestHealthKitAccess() {
        guard HKHealthStore.isHealthDataAvailable() else {
            print("HealthKit is not available on this device.")
            return
        }
 
      
        // Use HKObjectType.visionPrescription() to get the vision prescription type
    let healthKitTypesToRead: Set<HKObjectType> = [
        HKObjectType.visionPrescriptionType() ]
    
        healthStore.requestAuthorization(toShare: [], read: healthKitTypesToRead) { success, error in
            if success {
                DispatchQueue.main.async {
                    healthKitAuthorized = true
                    fetchVisionPrescriptions()
                }
            } else if let error = error {
                print("Error requesting HealthKit authorization: \(error.localizedDescription)")
            }
        }
    }

It is triggered in the body of ContentView:

VStack(spacing: 20) {
                    if healthKitAuthorized {
                        Text("Left Eye Cylinder: \(leftEyeCylinder)")
                        Text("Right Eye Cylinder: \(rightEyeCylinder)")
                    } else {
                        Text("Requesting HealthKit Access...")
                    }
                }
                .padding()
                .onAppear(perform: requestHealthKitAccess)

Health Kit is added to the project's capabilities and target properties include Privacy - Health Records / Share Usage.

Upvotes: 0

Views: 41

Answers (0)

Related Questions