I've written a basic iPhone app that reads Weight from HealthKit successfully, but my corresponding WatchOS app only returns empty results. I'm using the same HealthKit code on both platforms. I know the authorisation works on the Watch, because authorisation request returns isEnabled=success.
The behavior is the same on the simulators and the hardware devices, and the Phone returns the right weight, but the watch returns a result set with 0 samples (results?.count=0
). The HealthKit capability is enabled for both the watch and phone targets in the same project. I'm using WatchOS 2 and Xcode 7.0.1.
Could you help me understand why the watch returns no results please?
ViewController code for the iPhone
@IBAction func btnReadWeight(sender: AnyObject) {
HealthKit().recentWeight() { weight, error in
dispatch_async( dispatch_get_main_queue(), { () -> Void in
self.txtWeight.text=String(format:"%.1f",weight)
})
}
}
InterfaceController code on the Watch
@IBAction func btnReadWeight() {
HealthKit().recentWeight() { weight, error in
dispatch_async( dispatch_get_main_queue(), { () -> Void in
self.myLabel.setText(String(format:"%.1f",weight))
})
}
}
Healthkit code (identical on iPhone and Watch)
func recentWeight(completion: (Double, NSError?) -> () )
{
let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
let today = NSDate()
let querystart = NSCalendar.currentCalendar().dateByAddingUnit(
.Day,
value: -365, // since a year ago
toDate: today,
options: NSCalendarOptions(rawValue:0))
let predicate = HKQuery.predicateForSamplesWithStartDate(querystart , endDate: NSDate(), options: .None)
let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in
var recentweight: Double = 0
print(results?.count )
if results?.count > 0
{
for result in results as! [HKQuantitySample]
{
recentweight = result.quantity.doubleValueForUnit(HKUnit.gramUnit())/1000.0
}
}
completion(recentweight, error)
}
healthKitStore.executeQuery(query)
}