You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI从HealthKit读取视力处方遇授权异常求助

HealthKit读取隐形眼镜处方授权失败问题解决

问题背景

尝试读取HealthKit中的隐形眼镜处方(获取cylinder等参数)时,触发授权不允许的崩溃,报错信息如下:

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

当前使用的授权请求代码及触发逻辑见下方,已为项目添加Health Kit功能并配置了Privacy - Health Records / Share Usage权限。

当前代码

授权请求方法

private func requestHealthKitAccess() {
    guard HKHealthStore.isHealthDataAvailable() else {
        print("HealthKit is not available on this device.")
        return
    }

    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)")
        }
    }
}

视图触发代码

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

解决步骤

  1. 补充Info.plist权限描述
    视力处方属于Health Records范畴,必须在Info.plist中添加NSHealthRecordsUsageDescription键,值为明确的权限申请说明(比如"读取您的视力处方信息以提供配镜相关服务")。仅在目标属性中配置权限不够,Info.plist的描述是系统要求的必填项。

  2. 确认HealthKit功能配置完整
    进入项目的Signing & Capabilities页面,找到Health Kit模块,确保勾选了Clinical Health Records选项(部分Xcode版本中该选项在Health Kit功能下),这是访问视力处方这类临床记录的必要配置。

  3. 验证设备兼容性
    Health Records功能仅支持iOS 11及以上版本的iPhone设备,iPad不支持该功能。测试时请使用符合要求的设备。

  4. 重置权限状态
    前往设备的设置-隐私与安全性-健康,找到你的App,移除所有已授权的权限,重启App后重新发起授权请求,避免旧的权限缓存导致异常。

  5. 确认HealthStore实例初始化正确
    确保healthStore变量已在合适的位置(比如视图初始化时)完成实例化,避免请求授权时使用未初始化的实例。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 22:02:39