2017-10-09 94 views
0

我从我的目标c应用程序中读取我iPhone的健康值。 我只需要阅读最近10天,但我无法做一个查询来做到这一点。如何从healthkit获得最近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(529279732.871222 “的NSDate”)日期和结束日期> = CAST(527983732.871222 “的NSDate”) )

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

+0

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

回答

0

日期很简单。我已经为此here发布了更长的解释。

因此,一个简单的数字被放入声明。这是你的日期的数字表示。将该号码作为日期处理,将其转换为给定类型"NSDATE"

0

夫特4溶液:

在我的实施例I使用的便利方法HKQuery.predicateForSamples,这是为样品,其开始和结束日期落在指定时间间隔内的谓词。

您需要阅读的最后10 以下是如何从现在Date()

为-10透水天

的startDate 10日得到一个日期是:Calendar.current.date(byAdding: .day, value: -10, to: Date())!

注意 :您可以使用您想要的下一个和上一个日期的日期,只需更改Date()。

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

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

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

为u可以在我的谓语我加入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) 

希望能做到这一点。