Здесь я создал образец проекта для вас, где я внес некоторые изменения в ваш код, который показан ниже, и для этого добавлены комментарии:
import UIKit
import HealthKit
class ViewController: UIViewController {
//add a tableview to your storyboard and connect delegate and datasource
@IBOutlet weak var tblHeartRateData: UITableView!
let healthStore = HKHealthStore()
//create an array of HKSample which will hold your data from healthkit or you can create a custom class for that
var heartRateData: [HKSample]?
override func viewDidLoad() {
super.viewDidLoad()
//Get data access permission
getHealthKitPermission()
}
@IBAction func getHeartRate(_ sender: Any) {
getTodaysHeartRate { (result) in
DispatchQueue.main.async {
//Here you will get your healthkit data.
self.heartRateData = result
//Once you get it reload your table view
self.tblHeartRateData.reloadData()
}
}
}
//Permission
func getHealthKitPermission() {
let healthkitTypesToRead = NSSet(array: [
HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) ?? ""
])
healthStore.requestAuthorization(toShare: nil, read: healthkitTypesToRead as? Set) { (success, error) in
if success {
print("Permission accept.")
} else {
if error != nil {
print(error ?? "")
}
print("Permission denied.")
}
}
}
func getTodaysHeartRate(completion: (@escaping ([HKSample]) -> Void)) {
print("func")
let heartRateType:HKQuantityType = HKQuantityType.quantityType(forIdentifier: .heartRate)!
//predicate
let startDate = Date() - 2 * 24 * 60 * 60
let endDate = Date()
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])
//descriptor
let sortDescriptors = [
NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
]
let heartRateQuery = HKSampleQuery(sampleType: heartRateType,
predicate: predicate,
limit: Int(HKObjectQueryNoLimit),
sortDescriptors: sortDescriptors)
{ (query:HKSampleQuery, results:[HKSample]?, error:Error?) -> Void in
guard error == nil else { print("error"); return }
//Here I have added completion which will pass data when button will tap.
completion(results!)
}
healthStore.execute(heartRateQuery)
}
}
//TableView Methods.
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return heartRateData?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HeartDataTableViewCell
let heartRateUnit:HKUnit = HKUnit(from: "count/min")
let heartData = self.heartRateData?[indexPath.row]
guard let currData:HKQuantitySample = heartData as? HKQuantitySample else { return UITableViewCell()}
cell.lblHeartRate.text = "Heart Rate: \(currData.quantity.doubleValue(for: heartRateUnit))"
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 106
}
}
для получения дополнительной информации проверьте наш ЭТО демонстрационный проект.
И ваш результат будет:
![enter image description here](https://i.stack.imgur.com/V8uXT.gif)