让我们说一个应用程序请求授权将Health和碳水化合物写入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")
}
})
这将提示用户允许该应用程序写入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)
}
}
由于Apple不允许应用程序查看哪些HealthKit项目是可写的,因此无法检测到只写脂肪。这个问题有方法解决吗?感谢。
答案 0 :(得分:1)
Apple不允许应用查询可以写入哪些HealthKit类型,这是不正确的。您可能正在考虑读取授权,这是不可查询的。您可以authorizationStatus(for:)
使用HKHealthStore
至determine whether your app has write authorization。如果它返回notDetermined
或sharingDenied
,那么您的应用就没有授权。