我希望我的 iOS 应用程序能够与 Apple 的 HealKit 交互。
为了请求授权,我使用了这几行:
public func requestHealthkit() {
let healthStore = HKHealthStore()
var shareTypes = Set<HKSampleType>()
shareTypes.insert(HKSampleType.workoutType())
var readTypes = Set<HKObjectType>()
readTypes.insert(HKObjectType.workoutType())
healthStore.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) -> Void in
if success {
print("[HealthKit] request Authorization succeed!")
} else {
print("[HealthKit] request Authorization failed!")
}
if let error = error { print("[HealthKit] An error occurred: \(error)") }
}
}
编辑1(使用这种方式也行不通):
healthStore.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) in
print("I'm not called. However! :p")
}
编辑2(这是我的info.plist):
我已将 NSHealthUpdateUsageDescription 添加到 info.plist
文件中,并启用了运行状况工具包功能。
这些是我的功能设置:
但是调用函数 requestHealthkit()
将工作也不会产生任何错误消息或日志,只是 -> N-O-T-H-I-N-G。
这是请求 HealthKit 授权的正确方法还是我做的事情完全错误? (2.场景是很可能的情况)
非常感谢您的帮助,谢谢。
最佳答案
我已成功提交申请表。看看另一个问题( HealthKit - requestAuthorization(toShare:read:completion:) always succeeds )。看来您的集合中使用的类型不是预期的。
override func viewDidAppear(_ animated: Bool) {
if HKHealthStore.isHealthDataAvailable() {
if let hk = (UIApplication.shared.delegate as! AppDelegate?)?.healthStore {
self.requestHealthkit(hk)
}
}
}
private func requestHealthkit(_ healthStore:HKHealthStore) {
let writableTypes: Set<HKSampleType> = [
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!,
HKWorkoutType.workoutType(),
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!,
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)!,
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
]
let readableTypes: Set<HKSampleType> = [
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!,
HKWorkoutType.workoutType(),
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!,
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)!,
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
]
healthStore.requestAuthorization(toShare: writableTypes, read: readableTypes) { (success, error) -> Void in
if success {
print("[HealthKit] request Authorization succeed!")
} else {
print("[HealthKit] request Authorization failed!")
}
if let error = error { print("[HealthKit] An error occurred: \(error)") }
}
}
关于ios - swift:如何请求 HealtKit 许可?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48509061/