swift:如何申请HealtKit权限?

时间:2018-01-29 19:59:27

标签: ios swift permissions authorization

我希望我的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文件并启用了运行状况工具包功能。

image 1

这些是我的功能设置:

image 2

但是调用函数requestHealthkit() 将会工作,也不会产生任何错误消息或日志,只有 - &gt; N-O-T-H-I-N-G

这是请求HealthKit授权的正确方法还是我做错了什么? ( 2.情景是非常可能的情况

非常感谢帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

我已成功提交申请表。看看这个问题(HealthKit - requestAuthorization(toShare:read:completion:) always succeeds)。看起来您的集合中使用的类型不是预期的。

+============+===========+===============+======+
| Patient ID | Hand Used | Ambidextrous? | Time |
+============+===========+===============+======+
|         01 | Right     | Yes           |   12 |
+------------+-----------+---------------+------+
|         01 | Right     | Yes           |   10 |
+------------+-----------+---------------+------+
|         01 | Right     | Yes           |   11 |
+------------+-----------+---------------+------+
|         01 | Left      | Yes           |   13 |
+------------+-----------+---------------+------+
|         01 | Right     | Yes           |   12 |
+------------+-----------+---------------+------+
|         02 | Right     | No            |    9 |
+------------+-----------+---------------+------+
|         02 | Right     | No            |    7 |
+------------+-----------+---------------+------+
|         02 | Right     | No            |    8 |
+------------+-----------+---------------+------+
|         03 | Left      | Yes           |    8 |
+------------+-----------+---------------+------+
|         03 | Right     | Yes           |    8 |
+------------+-----------+---------------+------+