0

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)
}
solipsia
  • 3
  • 2

1 Answers1

2

There are two behaviors that could explain what you are seeing:

(1) All samples saved on the watch sync to the phone to be recorded permanently. The same is not true for samples saved on the phone though. The watch has limited storage capacity and is not as fast as your phone so storing a complete database of all samples on the watch is not feasible. If the weight sample originated from the phone then it won't be present on the watch.

(2) To limit the overall size of the HealthKit database on the watch, samples that were saved on the watch expire after about a week and become no longer accessible. See the HKHealthStore documentation.

Allan
  • 7,039
  • 1
  • 16
  • 26