使用 HealthKit 的异常

Exception Using HealthKit

我正在使用 Xcode 创建带有 HealthKit 的应用程序,但每当我尝试在 iOS 模拟器中授权 HealthKit 时,它就会崩溃。我的代码在底部。有谁知道如何解决这个问题?

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: "com.TestHKTutorial", 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)
  }
}

}

您的 healthKitTypesToRead 和 healthKitTypesToWrite 集包含 HKObjectTypes 数组,而不仅仅是包含 HKObjectTypes。试试这个:

let healthKitTypesToRead : Set = [
    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 = [
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)!,
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!,
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!,
    HKQuantityType.workoutType()
]