0

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
 }
Sam Spencer
  • 8,492
  • 12
  • 76
  • 133
Johnd
  • 584
  • 2
  • 6
  • 21

1 Answers1

0

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.

OOPer
  • 47,149
  • 6
  • 107
  • 142
  • Worked great! Thank you! – Johnd Jun 27 '17 at 23:32
  • 1
    Note that generating the label text this way is never going to localize properly, the string returned from the `description` method of `HKQuantity` is for debugging purposes only. If what you want to do is display a localized string representation you need to use something like `NSMeasurementFormatter`. – Allan Jun 29 '17 at 03:00