2017-06-05 28 views
0

比方说,一个应用程序请求授权写脂肪和碳水化合物,以HealthKit:HealthKit无法与多个条目写HKSample如果某些条目类型的由用户不允许

func dataTypesToWrite() -> NSSet { 
    return NSSet(objects: 
     HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCarbohydrates)!, 
     HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryFatTotal)! 
    ) 
} 

healthStore.requestAuthorization(toShare: dataTypesToWrite() as? Set<HKSampleType>, read: nil, completion: { (success, error) -> Void in 
    if success { 
     print("completed") 
    } 
}) 

这将提示用户允许应用程序写入HealthKit。如果用户允许写脂肪和碳水化合物,一切都很好。但是,如果他们只选择允许之一,与脂肪和碳水化合物的HKSample写入HealthKit,该条目将不会显示:

func foodCorrelationForFoodItem(foodNutrients: Dictionary<String, Double>, foodTitle: String) -> HKCorrelation { 
    let nowDate: Date = Date() 

    let consumedSamples: Set<HKSample> = [ 
     HKQuantitySample(
      type: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCarbohydrates)!, 
      quantity: HKQuantity(unit: HKUnit.gram(), doubleValue: 5.0), 
      start: nowDate, 
      end: nowDate), 
     HKQuantitySample(
      type: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryFatTotal)!, 
      quantity: HKQuantity(unit: HKUnit.gram(), doubleValue: 10.0), 
      start: nowDate, 
      end: nowDate) 
    ] 

    let foodType: HKCorrelationType = HKCorrelationType.correlationType(forIdentifier: HKCorrelationTypeIdentifier.food)! 
    let foodCorrelationMetadata: [String: AnyObject] = [HKMetadataKeyFoodType: foodTitle as AnyObject] 

    let foodCorrelation: HKCorrelation = HKCorrelation(type: foodType, start: nowDate, end: nowDate, objects: consumedSamples, metadata: foodCorrelationMetadata) 

    return foodCorrelation 
} 


self.healthStore.save(foodCorrelationForFoodItem) { (success, error) in 
    if let error = error { 
     print(error) 
    } 
} 

因为苹果不允许应用程序,看看哪些HealthKit项目是可写的,不可能检测到,例如只应写出脂肪。有针对这个的解决方法吗?谢谢。

回答

1

Apple确实不允许应用程序查询它可以写入哪些HealthKit类型。您可能正在考虑读取授权,这是不可查询的。您可以在HKHealthStoredetermine whether your app has write authorization之间使用authorizationStatus(for:)。如果它返回notDeterminedsharingDenied那么你的应用程序没有授权。