Ios 如何从healthkit获得最后10天?

Ios 如何从healthkit获得最后10天?,ios,objective-c,nsdate,nspredicate,healthkit,Ios,Objective C,Nsdate,Nspredicate,Healthkit,我正在从objective c应用程序中读取iPhone的健康值。 我只需要阅读过去10天的内容,但我无法通过查询来完成这项工作 我正在尝试使用以下代码将查询添加到谓词中: NSPredicate *explicitforDay = [NSPredicate predicateWithFormat:@"%K >= %@ AND %K <= %@", HKPredicateKeyPathDateComponents, startDateComponents, HKPredicate

我正在从objective c应用程序中读取iPhone的健康值。 我只需要阅读过去10天的内容,但我无法通过查询来完成这项工作

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

NSPredicate *explicitforDay =
[NSPredicate predicateWithFormat:@"%K >= %@ AND %K <= %@",
 HKPredicateKeyPathDateComponents, startDateComponents,
 HKPredicateKeyPathDateComponents, endDateComponents];
NSPredicate*explicitforDay=
[NSPredicate predicateWithFormat:@“%K>=%”和%K=%%@,HKPredicateKeyPathStartDate
,HKPredicateKeyPathEndDate],myFirstDate,myEndDate];
但在输出中,我可以看到如下内容:

(开始日期= 铸造(527983732.871222,“NSDate”))

为什么打印类型转换和错误的日期值?
谢谢

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


因此,在语句中放入一个简单的数字。它是日期的数字表示形式。要将数字视为日期,将其转换为给定类型
“NSDATE”

Swift 4解决方案:

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

 let predicate = HKQuery.predicateForSamples(
                     withStart: startDate.beginningOfDay(), 
                     end: endDate, 
                     options: [.strictStartDate,.strictEndDate])
你需要读最后10篇 以下是如何获取日期-从现在起10天
date()

前10天

开始日期是:
Calendar.current.date(通过添加:.day,值:-10,到:date())

注意:您可以使用您想要的下一天和前一天的日期,只需更改
日期(

结束日期为:
Date()
-->(当前日期)

因此,我的谓词在指定的时间间隔内看起来像

 let predicate = HKQuery.predicateForSamples(
                     withStart: startDate.beginningOfDay(), 
                     end: endDate, 
                     options: [.strictStartDate,.strictEndDate])
正如您在谓词中看到的,我正在添加
beginingofday()
方法,这将允许我从00:00开始日期

beginingofday()
方法说明:

func beginningOfDay() -> Date {
        let beginningOfDay = Calendar.current.startOfDay(for: self)
        return beginningOfDay
    }
还可以创建谓词格式字符串以创建等效谓词,如中所述

让explicitTimeInterval=NSPredicate(格式:“%K>=%@和%K<%@”,
HKPredicateKeyPathEndDate,myStartDate,
HKPredicateKeyPathStartDate,myEndDate)

希望,它能起作用。

我在代码中看不到任何打印命令,也看不到日期的实际值。因此,很难说打印输出是否正确。
let explicitTimeInterval = NSPredicate(format: "%K >= %@ AND %K < %@",
                                       HKPredicateKeyPathEndDate, myStartDate,
                                       HKPredicateKeyPathStartDate, myEndDate)