gpt4 book ai didi

ios - 使用iwatch快速提取心率代码

转载 作者:行者123 更新时间:2023-11-28 07:21:38 24 4
gpt4 key购买 nike

我使用下面的代码来提取心率,但是当我在我的自定义类中使用它时,它说 self.heartRateQuery 没有在类中定义。它的正确原因是我的类中没有 heartRateQuery。我是 swift 的新手。你能告诉我如何处理这个吗?我只想提取心率。那么我应该在代码中做什么修正以及将代码放在下面的什么地方。在我的界面 Controller 中?


// Creating the sample for the heart rate
guard let sampleType: HKSampleType =
HKObjectType.quantityType(forIdentifier: .heartRate) else {
return
}

/// Creating an observer, so updates are received whenever HealthKit’s
// heart rate data changes.
self.heartRateQuery = HKObserverQuery.init(
sampleType: sampleType,
predicate: nil) { [weak self] _, _, error in
guard error == nil else {
log.warn(error!)
return
}

/// When the completion is called, an other query is executed
/// to fetch the latest heart rate
self.fetchLatestHeartRateSample(completion: { sample in
guard let sample = sample else {
return
}

/// The completion in called on a background thread, but we
/// need to update the UI on the main.
DispatchQueue.main.async {

/// Converting the heart rate to bpm
let heartRateUnit = HKUnit(from: "count/min")
let heartRate = sample
.quantity
.doubleValue(for: heartRateUnit)

/// Updating the UI with the retrieved value
self?.heartRateLabel.setText("\(Int(heartRate))")
}
})
}
}

public func fetchLatestHeartRateSample(
completion: @escaping (_ sample: HKQuantitySample?) -> Void) {

/// Create sample type for the heart rate
guard let sampleType = HKObjectType
.quantityType(forIdentifier: .heartRate) else {
completion(nil)
return
}

/// Predicate for specifiying start and end dates for the query
let predicate = HKQuery
.predicateForSamples(
withStart: Date.distantPast,
end: Date(),
options: .strictEndDate)

/// Set sorting by date.
let sortDescriptor = NSSortDescriptor(
key: HKSampleSortIdentifierStartDate,
ascending: false)

/// Create the query
let query = HKSampleQuery(
sampleType: sampleType,
predicate: predicate,
limit: Int(HKObjectQueryNoLimit),
sortDescriptors: [sortDescriptor]) { (_, results, error) in

guard error == nil else {
print("Error: \(error!.localizedDescription)")
return
}

completion(results?[0] as? HKQuantitySample)
}

self.healthStore.execute(query)
}~

最佳答案

您是否将 heartRateQuery 对象实例化为自定义类的属性?所以:

class MyCustomClass: SomeSuperClass, SomeProtocols {
var heartRateQuery: HKObserverQuery()?

[YOUR CODE HERE]

}

关于ios - 使用iwatch快速提取心率代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57832815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com