I've managed to call on HealthKit to fetch the most recent weight data. However when I run it, it includes a whole load of text as follows:
64 kg E457AF14-36D7-4547-AFAA-EF23DDD6642D "Health" (12.0), "iPhone10,4" (12.0)metadata: {
HKWasUserEntered = 1;
} (2018-10-12 13:12:00 +0100 - 2018-10-12 13:12:00 +0100)
Here is my code:
func getTodaysWeight(completion: @escaping (HKQuantitySample) -> Void) {
guard let weightSampleType = HKSampleType.quantityType(forIdentifier: .bodyMass) else {
print("Body Mass Sample Type is no longer available in HealthKit")
return
}
//1. Use HKQuery to load the most recent samples.
let mostRecentPredicate = HKQuery.predicateForSamples(withStart: Date.distantPast,
end: Date(),
options: [])
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate,
ascending: false)
let limit = 1
let sampleQuery = HKSampleQuery(sampleType: weightSampleType,
predicate: mostRecentPredicate,
limit: limit,
sortDescriptors: [sortDescriptor]) { (query, samples, error) in
//2. Always dispatch to the main thread when complete.
DispatchQueue.main.async {
guard let samples = samples,
let mostRecentSample = samples.first as? HKQuantitySample else {
print("getUserBodyMass sample is missing")
return
}
completion(mostRecentSample)
}
}
HealthStore.execute(sampleQuery)
}
////////////////////////////////////
private func updateWeightCountLabel() {
getTodaysWeight { (result) in
print("\(result)")
DispatchQueue.main.async {
self.totalWeight.text = "\(result)"
self.totalWeight.text = String(format:"%.2f")
print("\(result)")
}
}
}
I've tried truncating the end first of all. Obviously all of this text is still there but it's messy and not really acceptable.
I then tried to add the following code below the private func like I'd used in another ViewController to set to two decimals. Using this code below however just results in no result being shown in the UIlabel string.
self.totalWeight.text = String(format:"%.2f")
print("\(result)")
It's my first attempt at any sort of programming, so I'm using this first app personally as an ongoing learning process, slowly adding, changing, breaking as I go along.
You’re printing the result from that completion handler, which is HKQuantitySample
. This object contains several properties, so printing the whole thing will give you the output you’re currently seeing with all the information about the object. Try printing result.quantity
for just the measurement. Take a look at this page from Apple about that type.