【问题标题】:Can't read HealthKit samples on WatchOS 2, but it works on iOS无法在 WatchOS 2 上读取 HealthKit 示例,但它适用于 iOS
【发布时间】: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


    【解决方案1】:

    有两种行为可以解释您所看到的:

    (1) 手表上保存的所有样本同步到手机以永久记录。但是,保存在手机上的样本并非如此。手表的存储容量有限,速度不如手机快,因此在手表上存储所有样本的完整数据库是不可行的。如果重量样本来自手机,那么它不会出现在手表上。

    (2) 为了限制手表上 HealthKit 数据库的整体大小,保存在手表上的样本会在大约一周后过期,并且不再可访问。见the HKHealthStore documentation

    【讨论】:

    • 天才,谢谢。我没有考虑设备之间的 HealthKit 样本流。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多