【问题标题】:HealthKit - requestAuthorization(toShare:read:completion:) always succeedsHealthKit - requestAuthorization(toShare:read:completion:) 总是成功
【发布时间】:2017-01-07 01:57:03
【问题描述】:

我正在使用 Xcode 8 beta 6,并且我正在请求访问 Health App。当完成处理程序返回时,请求授权的方法requestAuthorization(toShare:read:completion:) 总是产生一个true - 在我下面的代码中是success。即使我拒绝模拟器中的所有内容,我也会收到true。 这是我处理授权的代码。是我的代码有问题还是这是 Xcode 错误?

import Foundation
import HealthKit

class HealthManager {
    private let healthStore = HKHealthStore()

    class var sharedInstance: HealthManager {
        struct Singleton {
            static let instance = HealthManager()
        }
        return Singleton.instance
    }

    private var isAuthorized: Bool? = false

    func authorizeHealthKit(completion: ((_ success: Bool) -> Void)!) {
        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)!]

        guard HKHealthStore.isHealthDataAvailable() else {
            completion(false)
            return
        }

        // Request Authorization
        healthStore.requestAuthorization(toShare: writableTypes, read: readableTypes) { (success, error) in

            if success {
                completion(true)
                self.isAuthorized = true
            } else {
                completion(false)
                self.isAuthorized = false
                print("error authorizating HealthStore. You're propably on iPad \(error?.localizedDescription)")
            }
        }
    }
}

感谢您的帮助!

【问题讨论】:

  • 你能发布你的最终代码是什么样子的吗?

标签: ios swift xcode healthkit xcode8-beta6


【解决方案1】:

您误解了成功标志的含义。 YES 表示权限屏幕已成功显示,NO 表示权限屏幕出现错误。来自 Apple 的 HealthKit 文档:

一个布尔值,指示请求是否已成功处理。此值不指示是否实际授予权限。如果处理请求时发生错误,则该参数为 NO;否则为YES。

如果要检查是否有权限写入数据,需要使用authorizationStatus(for:),但注意不能确定读取数据的权限。

此方法检查保存数据的授权状态。

为帮助防止敏感健康信息可能泄露,您的应用无法确定用户是否已授予读取数据的权限。如果您没有获得许可,它只会显示为在 HealthKit 存储中没有请求类型的数据。如果您的应用被授予共享权限但没有读取权限,则您只能看到您的应用写入商店的数据。来自其他来源的数据仍然隐藏。

文档在这里:https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKHealthStore_Class/index.html

【讨论】:

  • 谢谢。就是这样。我应该在保存样本之前使用“authorizationStatus(for:)”!
猜你喜欢
  • 2018-10-18
  • 2016-03-30
  • 1970-01-01
  • 2020-09-09
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多