【发布时间】:2015-10-02 11:15:01
【问题描述】:
我编写了一个基本的 iPhone 应用程序,它成功地从 HealthKit 读取体重,但我相应的 WatchOS 应用程序只返回空结果。我在两个平台上使用相同的 HealthKit 代码。我知道授权在 Watch 上有效,因为授权请求返回 isEnabled=success。
在模拟器和硬件设备上的行为是相同的,并且手机返回正确的权重,但手表返回一个包含 0 个样本的结果集 (results?.count=0)。同一项目中的手表和手机目标都启用了 HealthKit 功能。我正在使用 WatchOS 2 和 Xcode 7.0.1。
你能帮我理解为什么手表没有返回结果吗?
iPhone 的 ViewController 代码
@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)
})
}
}
Watch 上的 InterfaceController 代码
@IBAction func btnReadWeight() {
HealthKit().recentWeight() { weight, error in
dispatch_async( dispatch_get_main_queue(), { () -> Void in
self.myLabel.setText(String(format:"%.1f",weight))
})
}
}
Healthkit 代码(在 iPhone 和 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)
}
【问题讨论】:
标签: ios iphone swift watchos-2 healthkit