Let's say an app requests authorization to write fat and carbohydrates to HealthKit:
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")
}
})
This will prompt the user to allow the app to write to HealthKit. If the user allows both fat and carbs to be written, all is well. But if they only choose to allow one, and an HKSample with fat and carbs is written to HealthKit, that entry won't show up:
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)
}
}
Since Apple doesn't allow applications to see which HealthKit items are writeable, it's impossible to detect if e.g. only fat should be written. Is there a solution to this? Thanks.
It's not true that Apple does not allow apps to query which HealthKit types it can write to. You might be thinking of read authorization, which is not queryable. You can use authorizationStatus(for:)
on HKHealthStore
to determine whether your app has write authorization. If it returns notDetermined
or sharingDenied
then your app does not have authorization.