Extra Characters when pulling from HealthKit

82 views Asked by At

When I pull my HealthKit data using HKSampleQuery, I create an array and then populate a tableview. However, when I do this my tableViewCell has many other characters after the blood sugar number. Here's a screenshot of the cell:

enter image description here

Heres where I query the data. Any help please!

    let endDate = NSDate()
    let startDate = NSCalendar.current.date(byAdding: .day, value: number, to: endDate as Date)
    let sampleType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose)
    let mostRecentPredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate as Date, options: [])
    let query = HKSampleQuery(sampleType: sampleType!, predicate: mostRecentPredicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { (query, results, error) in
        if let results = results as? [HKQuantitySample] {
            self.bloodGlucose = results
        }
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
    healthStore.execute(query)

Here's where I setup the tableview...

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return bloodGlucose.count
  }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let currentCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
                let sugar = bloodGlucose[indexPath.row]
                currentCell.textLabel?.text = "\(sugar)"
                currentCell.detailTextLabel?.text = dateFormatter.string(from: sugar.startDate)
                return currentCell
 }
1

There are 1 answers

2
OOPer On BEST ANSWER

Seems you are showing whole String representation of HKQuantitySample. If you want to show only quantity of the HKQuantitySample, why don't you use its quantity property?

currentCell.textLabel?.text = "\(sugar.quantity)"

By the way, you better declare your endDate as Date (not NSDate):

let endDate = Date()
let startDate = Calendar.current.date(byAdding: .day, value: number, to: endDate)
let sampleType = HKSampleType.quantityType(forIdentifier: .bloodGlucose)
let mostRecentPredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate)

Generally, non-NS types work better with Swift.