- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试构建一个从 Apple Health 应用程序读取数据的应用程序。
我的应用请求用户允许访问来自 HealthKit 的数据。当我在授予应用程序权限后尝试读取数据时,我收到此错误消息:
The operation couldn't be completed. (Foundation._GenericObjCError error 0.)
Xcode 上没有错误显示;只有在设备上进行测试时才会出现此消息。
这是获得 HealthKit 许可的代码部分:
import Foundation
import HealthKit
class HealthKitSetupAssistant{
private enum HealthkitSetupError: Error{
case notAvailableOnDevice
case dataTypeNotAvailable
}
class func authorizeHealthKit(completion: @escaping (Bool, Error?) -> Swift.Void){
// 1. Check to see if HealthKit is available on this device
guard HKHealthStore.isHealthDataAvailable() else{
completion(false, HealthkitSetupError.notAvailableOnDevice)
return
}
//2. Prepare the data types that will interact with HealthKit
guard let dateOfBirth = HKObjectType.characteristicType(forIdentifier: .dateOfBirth),
let bloodType = HKObjectType.characteristicType(forIdentifier: .bloodType),
let biologicalSex = HKObjectType.characteristicType(forIdentifier: .biologicalSex),
let bodyMassIndex = HKObjectType.quantityType(forIdentifier: .bodyMassIndex),
let height = HKObjectType.quantityType(forIdentifier: .height),
let bodyMass = HKObjectType.quantityType(forIdentifier: .bodyMass),
let activeEnergy = HKObjectType.quantityType(forIdentifier: .activeEnergyBurned) else{
completion(false, HealthkitSetupError.dataTypeNotAvailable)
return
}
//3. Prepare a list of types you want HealthKit to read and write
let healthKitTypesToWrite: Set<HKSampleType> = [bodyMassIndex, activeEnergy, HKObjectType.workoutType()]
let healthKitTypesToRead: Set<HKObjectType> = [dateOfBirth, bloodType, biologicalSex, bodyMassIndex, height, bodyMass, HKObjectType.workoutType()]
//4. Request Authorization
HKHealthStore().requestAuthorization(toShare: healthKitTypesToWrite, read: healthKitTypesToRead) { (success, error) in
completion(success, error)
}
}
}
这是尝试从 HealthKit 读取数据的代码部分:
import Foundation
import HealthKit
class ProfileDataStore {
class func getAgeSexAndBloodType() throws -> (age: Int,
biologicalSex: HKBiologicalSex,
bloodType: HKBloodType) {
let healthKitStore = HKHealthStore()
do {
//1. This method throws an error if these data are not available.
let birthdayComponents = try healthKitStore.dateOfBirthComponents()
let biologicalSex = try healthKitStore.biologicalSex()
let bloodType = try healthKitStore.bloodType()
//2. Use Calendar to calculate age.
let today = Date()
let calendar = Calendar.current
let todayDateComponents = calendar.dateComponents([.year],
from: today)
let thisYear = todayDateComponents.year!
let age = thisYear - birthdayComponents.year!
//3. Unwrap the wrappers to get the underlying enum values.
let unwrappedBiologicalSex = biologicalSex.biologicalSex
let unwrappedBloodType = bloodType.bloodType
return (age, unwrappedBiologicalSex, unwrappedBloodType)
}
}
class func getMostRecentSample(for sampleType: HKSampleType,
completion: @escaping (HKQuantitySample?, Error?) -> Swift.Void) {
//1. Use HKQuery to load the most recent samples.
let mostRecentPredicate = HKQuery.predicateForSamples(withStart: Date.distantPast,
end: Date(),
options: .strictEndDate)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate,
ascending: false)
let limit = 1
let sampleQuery = HKSampleQuery(sampleType: sampleType,
predicate: mostRecentPredicate,
limit: limit,
sortDescriptors: [sortDescriptor]) { (query, samples, error) in
//2. Always dispatch to the main thread when complete.
DispatchQueue.main.async {
guard let samples = samples,
let mostRecentSample = samples.first as? HKQuantitySample else {
completion(nil, error)
return
}
completion(mostRecentSample, nil)
}
}
HKHealthStore().execute(sampleQuery)
}
class func saveBodyMassIndexSample(bodyMassIndex: Double, date: Date) {
//1. Make sure the body mass type exists
guard let bodyMassIndexType = HKQuantityType.quantityType(forIdentifier: .bodyMassIndex) else {
fatalError("Body Mass Index Type is no longer available in HealthKit")
}
//2. Use the Count HKUnit to create a body mass quantity
let bodyMassQuantity = HKQuantity(unit: HKUnit.count(),
doubleValue: bodyMassIndex)
let bodyMassIndexSample = HKQuantitySample(type: bodyMassIndexType,
quantity: bodyMassQuantity,
start: date,
end: date)
//3. Save the same to HealthKit
HKHealthStore().save(bodyMassIndexSample) { (success, error) in
if let error = error {
print("Error Saving BMI Sample: \(error.localizedDescription)")
} else {
print("Successfully saved BMI Sample")
}
}
}
}
如有任何建议或对错误消息的解释,我们将不胜感激!
最佳答案
您应该在您的应用程序中只创建一个 HKHealthStore 实例并重用该实例。我不知道您的应用程序是如何构建的,所以我不知道保存对 HKHealthStore 的引用的最佳位置在哪里,但 AppDelegate 始终是一个选项。
关于ios - 如何修复此错误 : 'Foundation._GenericObjCError error 0. ' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56154855/
我正在尝试使用核心数据的批量删除功能。我有一个名为 Car 的实体。该实体的列名称 modelNumber 为 Int。我想删除所有型号早于 2000 的汽车。这是我的代码: func deleteC
我正在从 Swift 调用一些旧的 Objective-C 代码,它经常会抛出这个错误,即使看起来没有任何问题: do { try objCObject.someMethod() } catc
我正在尝试构建一个从 Apple Health 应用程序读取数据的应用程序。 我的应用请求用户允许访问来自 HealthKit 的数据。当我在授予应用程序权限后尝试读取数据时,我收到此错误消息: Th
我是一名优秀的程序员,十分优秀!