Swift中的HealthKit Auth

时间:2015-04-26 00:00:13

标签: ios swift health-kit

我一直在构建一个基本的应用程序来快速收集健康套件中的健身和其他数据,但是,我遇到了获得授权的问题

class HealthManager {

let healthKitStore:HKHealthStore = HKHealthStore()


func authorizeHealthKit(completion: ((success:Bool, error:NSError!) -> Void)!)
{
    // 1. Set the types you want to read from HK Store
let healthKitTypesToRead = Set(arrayLiteral:[
    HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth),
    HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBloodType),
    HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex),
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass),
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight),
    HKObjectType.workoutType()
    ])

// 2. Set the types you want to write to HK Store
let healthKitTypesToWrite = Set(arrayLiteral:[
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex),
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned),
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning),
    HKQuantityType.workoutType()
    ])

// 3. If the store is not available (for instance, iPad) return an error and don't go on.
if HKHealthStore.isHealthDataAvailable()
{
    let error = NSError(domain: "me.kebabman.healthkit", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"])
    if( completion != nil )
    {
        completion(success:false, error:error)
    }
    return;
}

// 4.  Request HealthKit authorization
  healthKitStore.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) { (success, error) -> Void in

    if( completion != nil )
    {
        completion(success:success,error:error)
    }
}
  }

}

从另一个类(我的视图控制器)我正在调用authoriseHealthKit函数 - 无论我改变什么我总是回来HealthKit在这个设备上不可用(使用iOS 8.3模拟器)

从阅读论坛开始,这应该有效,但我无法弄清楚原因。

由于

2 个答案:

答案 0 :(得分:1)

您的IF声明错误

此部分代码if HKHealthStore.isHealthDataAvailable() { return error ... }

应该是

if !HKHealthStore.isHealthDataAvailable() { return error ... }

if HKHealthStore.isHealthDataAvailable() { request authorization ... } else { return error... }

答案 1 :(得分:0)

您是否添加了权利?请检查此答案:Try HealthKit with the iOS Simulator without developer account。这很可能是你的问题。