【问题标题】:How can I get last 10 days from healthkit?我怎样才能从 healthkit 获得最后 10 天?
【发布时间】:2018-03-21 05:11:04
【问题描述】:

我正在从我的目标 c 应用程序中读取我的 iPhone 的健康值。 我只需要阅读过去 10 天的数据,但我无法进行查询。

我正在尝试使用以下代码将查询添加到谓词中:

NSPredicate *explicitforDay =
[NSPredicate predicateWithFormat:@"%K >= %@ AND %K <= %@",
 HKPredicateKeyPathDateComponents, startDateComponents,
 HKPredicateKeyPathDateComponents, endDateComponents];

然后我尝试了这个:

NSPredicate *explicitforDay = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ < %%@ AND %@ >= %%@", HKPredicateKeyPathStartDate
                                                                    , HKPredicateKeyPathEndDate], myFirstDate, myEndDate];

但在输出中我可以看到这样的一些:

(startDate = CAST(527983732.871222, "NSDate"))

为什么要打印 CAST 和错误的日期值? 谢谢!

【问题讨论】:

  • 我在您的代码中既没有看到任何打印命令,也没有看到日期的实际值。因此很难说打印出来的是否正确。

标签: ios objective-c nsdate nspredicate healthkit


【解决方案1】:

Swift 4 解决方案:

在我的示例中,我使用便捷方法HKQuery.predicateForSamples,这是开始和结束日期在指定时间间隔内的样本的谓词。

您需要阅读最后 10 个 这是从现在开始 -10 天后获取日期的方法Date()

过去 -10 天

开始日期是:Calendar.current.date(byAdding: .day, value: -10, to: Date())!

注意:您可以使用您想要的第二天和前一天的日期,只需更改Date()。

endDate 是:Date() -->(当前日期)

所以我的谓词看起来像一个指定的时间间隔。

 let predicate = HKQuery.predicateForSamples(
                     withStart: startDate.beginningOfDay(), 
                     end: endDate, 
                     options: [.strictStartDate,.strictEndDate])

正如你在我的谓词中看到的,我正在添加 beginningOfDay() 方法,这将允许我从 00:00 开始日期

beginningOfDay()方法说明:

func beginningOfDay() -> Date {
        let beginningOfDay = Calendar.current.startOfDay(for: self)
        return beginningOfDay
    }

您还可以创建谓词格式字符串来创建等效的谓词,如heathkitDoc 中所述。

let explicitTimeInterval = NSPredicate(format: "%K >= %@ AND %K < %@",
                                       HKPredicateKeyPathEndDate, myStartDate,
                                       HKPredicateKeyPathStartDate, myEndDate)

希望能成功。

【讨论】:

    【解决方案2】:

    日期是一个简单的数字。我已经对此here 发布了更长的解释。

    所以在语句中加入了一个简单的数字。它是您的日期的数字表示。要将数字视为日期,将其转换为给定类型 "NSDATE"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 2011-06-04
      • 2020-10-07
      • 1970-01-01
      • 2017-09-29
      相关资源
      最近更新 更多