我創建了一個應用程式來保存和讀取一些跑步和步行鍛煉資料到 HealthKit。我設法保存了資料,并在模擬器的 Health 應用程式上查看它,但是當我嘗試讀取資料時,樣本計數為 0。如果有人幫助我解決這個問題,我將不勝感激。
Xcode 12.5.1 / iOS 14.5
func AuthenticateHealthKit() {
print("AuthenticateHealthKit")
let typesToShare: Set = [
HKQuantityType.workoutType()
]
let typesToRead: Set = [
HKQuantityType.workoutType(),
HKQuantityType.quantityType(forIdentifier: .distanceWalkingRunning)!,
HKQuantityType.quantityType(forIdentifier: .height)!,
]
healthStore.requestAuthorization(toShare: typesToShare, read: typesToRead) { (success, error) in
if !success {
fatalError("Error requesting authorization from health store: \(String(describing: error)))")
} else {
print("Authenticated!")
}
}
}
func SaveData() {
let configuration = HKWorkoutConfiguration()
configuration.activityType = .running
configuration.locationType = Int.random(in: 0..<2) == 0 ? .indoor : .outdoor
let startDate = now - (86400 * 60.0)
let duration = 120.0
let endDate = startDate duration
let quantity = HKQuantity(unit: HKUnit.kilocalorie(), doubleValue: 20.0)
let distance = HKQuantity(unit: HKUnit.meter(), doubleValue: 1200)
let workout = HKWorkout(
activityType: configuration.activityType, start: startDate, end: endDate, duration: duration,
totalEnergyBurned: quantity, totalDistance: distance,
metadata: [HKMetadataKeyIndoorWorkout: true])
healthStore.save(workout) { success, _ in
if success {
print("SAVED WORKOUT!!!")
} else {
print("COULD NOT SAVE WORKOUT!!!")
}
}
}
func ReadData() {
let start = now - (86400 * 60.0)
let end = now
let predicate = HKQuery.predicateForSamples(withStart: start, end: end, options: [])
print("start : \(start)")
guard HKHealthStore.isHealthDataAvailable() else {
print("No data available!")
return
}
guard
let sampleType = HKSampleType.quantityType(
forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)
else {
fatalError("*** This method should never fail ***")
}
let query = HKSampleQuery(
sampleType: sampleType, predicate: predicate, limit: Int(HKObjectQueryNoLimit),
sortDescriptors: nil
) {
query, results, error in
guard let samples = results as? [HKQuantitySample] else {
print("Error")
return
}
for sample in samples {
print("sample : \(sample.quantity) \(sample.quantityType)")
}
DispatchQueue.main.async {
print("Update UI : \(samples.count)")
}
}
healthStore.execute(query)
}
這是ReadData方法的輸出
start : 2021-08-14 21:38:35 0000
Authenticated!
Update UI : 0
以下是 Health App 資料和權限(均在模擬器上)

uj5u.com熱心網友回復:
您正在撰寫鍛煉計劃,但想要閱讀長距離步行 跑步。保存鍛煉的距離屬性不會保存步行 跑步的距離示例。您需要創建該型別的樣本,為其請求身份驗證,并使用 HKHealthStore 上的 addSamples 方法保存和關聯鍛煉。
使用 HKWorkoutBuilder 會好得多,它是 beginCollection/add/endCollection/finishWorkout 方法,它將為您創建合適的 HKWorkout 物件。
uj5u.com熱心網友回復:
我設法保存了可以使用ReadData方法讀取的資料(查看原始問題)。這是新的SaveData方法:
let now = Date()
func SaveData() {
let configuration = HKWorkoutConfiguration()
configuration.activityType = .running
configuration.locationType = Int.random(in: 0..<2) == 0 ? .indoor : .outdoor
let builder = HKWorkoutBuilder(healthStore: healthStore, configuration: configuration, device: .local())
let sample = HKCumulativeQuantitySample(type: HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!, quantity: HKQuantity.init(unit: HKUnit.meter(), doubleValue: 1230), start: now - 3600, end: now)
builder.add([sample]) { success, error in
guard success else {
print("Error!")
return
}
print("Added Sample")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316656.html
