Swift UITableView 不会使用 Healthkit 中的值进行更新



我已经尝试了所有可以找到资源的方法,但我越来越绝望了。我正在尝试用用户锻炼信息填充UITableView。活动名称、开始日期和持续时间。由于某些原因,UITableView拒绝填充此信息。我认为问题可能出在异步/完成处理程序上,所以我添加了一个按钮来重新加载UITableView,但这也不起作用。我知道数组中有值,因为按钮成功地将它们打印到控制台,但reloadData()函数仍然无法填充表。

非常感谢您的帮助,因为我不知道还能尝试什么。。。

import UIKit
import HealthKit
class ViewController: UIViewController, UITableViewDataSource{

/* --------Global variables for queries ------------*/
let healthStore = HealthData.healthStore
let workoutType = HKObjectType.workoutType()


//Creating the table that shows activities
@IBOutlet weak var workoutTable: UITableView!

/* ---------- UI element definitions--------------- */

@IBAction func checkData(_ sender: UIButton){
print(dataValues.count) //this prints 10, which is correct
print(dataValues) //this prints the correct values.
DispatchQueue.main.async{
self.workoutTable.reloadData() //this doesn't work for some reason.
}
}


/*--------- Variables for the table objects --------*/
struct workoutStruct {
var workoutActivity: String
var workoutDate: Date
var workoutDuration: Double
}

var dataValues = [workoutStruct]()


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
requestAuthorization()
async{
let dataValues = await workoutQueryii()
self.dataValues = dataValues
DispatchQueue.main.async {
self.workoutTable.reloadData()
}
}

}

//function for setting the number of rows in the UI table
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return dataValues.count

}

//function for mapping the data from dataValues array to the table view.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

//use the current row as the array value
let workout = dataValues[indexPath.row]


//identify the cell in the table view
let cell = workoutTable.dequeueReusableCell(withIdentifier: "workoutCell", for: indexPath) as! CustomTableViewCell

cell.activityLabel.text = workout.workoutActivity
cell.dateLabel.text = funcDateFormatter(date: workout.workoutDate)
cell.durationLabel.text = workout.workoutDuration.formatted()

return cell
}

func workoutQueryii() async -> [workoutStruct] {
let sort = [NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)]
//this query finds the users workout samples based on the parameters set below.
let query = HKSampleQuery(
sampleType: workoutType,
predicate: nil,
limit: 10,
sortDescriptors: sort) { (query, resultsOrNil, error) in
self.dataValues = []
//process results
//create an array for the HKWorkout objects to be passed to in the query
var workoutsQ: [HKWorkout] = []

if let results = resultsOrNil {
for result in results {
if let workout = result as? HKWorkout {
//here's a workout object
workoutsQ.append(workout)
var dataValue = workoutStruct(
workoutActivity: workout.workoutActivityType.name,
workoutDate: workout.startDate,
workoutDuration: workout.duration )

self.dataValues.append(dataValue)

}

}

}

}

self.healthStore.execute(query)
print(dataValues.count) //this returns 0
return dataValues

}

//End of class
}

我曾尝试将async添加到workoutQuery函数中,但显然它已被弃用。我已经尝试用现有的名称数组填充表,这很有效,这样我就知道表设置正确了。我试过用这个按钮来重新加载数据,但似乎也不起作用。

这里是异步上下文。但是您的实现是不正确的。无论是在func声明中还是在调用它时,都不需要async修饰符。您可能应该更深入地了解swift并发是如何工作的。尤其是像这里有回调的老类型。

尽管如此,这应该会让你在这段时间内继续前进:

func workoutQueryii() {
let sort = [NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)]
//this query finds the users workout samples based on the parameters set below.
let query = HKSampleQuery(
sampleType: workoutType,
predicate: nil,
limit: 10,
sortDescriptors: sort) { (query, resultsOrNil, error) in
self.dataValues = []
//process results
//create an array for the HKWorkout objects to be passed to in the query
//var workoutsQ: [HKWorkout] = [] // don´t know what this is for. It´s not used later on in a meaningfull manner.

if let results = resultsOrNil {
for result in results {
if let workout = result as? HKWorkout {
//here's a workout object
//workoutsQ.append(workout) // don´t know what this is for
var dataValue = workoutStruct(
workoutActivity: workout.workoutActivityType.name,
workoutDate: workout.startDate,
workoutDuration: workout.duration )

self.dataValues.append(dataValue)

}

}
}

//reload table here after appending all values to the array
DispatchQueue.main.async {
workoutTable.reloadData()
}
}
self.healthStore.execute(query)
// code here executes emmediatly after the query started without waiting for it to complete.
}

viewDidLoad:

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

requestAuthorization()
workoutQueryii()
}

最新更新