2016-08-30 74 views
3

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

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

感谢您的帮助!

+1

你可以发布您的最终代码是什么样子? – Adrian

回答

6

你错误地解释了那个成功标志的含义。 YES表示权限屏幕已成功显示,NO表示显示权限屏幕时出现错误。从Apple的HealthKit文档:

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

如果要检查是否有权写入数据,则需要使用authorizationStatus(for:),但请注意,您无法确定读取数据的授权。

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

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

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

+0

谢谢。就是这样。在保存示例之前,我应该使用'authorizationStatus(for :)'! – heikomania