Reputation: 6253
I'm reading health values of my iPhone from my objective c app. I need only read the last 10 days, but I can't do a query to do this.
I'm trying add into a predicate the query with this code:
NSPredicate *explicitforDay =
[NSPredicate predicateWithFormat:@"%K >= %@ AND %K <= %@",
HKPredicateKeyPathDateComponents, startDateComponents,
HKPredicateKeyPathDateComponents, endDateComponents];
And then I tried this:
NSPredicate *explicitforDay = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ < %%@ AND %@ >= %%@", HKPredicateKeyPathStartDate
, HKPredicateKeyPathEndDate], myFirstDate, myEndDate];
But in output I can see some like this:
(startDate < CAST(529279732.871222, "NSDate") AND endDate >= CAST(527983732.871222, "NSDate"))
Why are printing a CAST and wrong date values? Thanks!
Upvotes: 0
Views: 1147
Reputation: 150
Swift 4 solution:
in my example i use the convenience method HKQuery.predicateForSamples
, this is a predicate for samples whose start and end dates fall within the specified time interval.
You need to read the last 10
Here's how to get a date -10 days from now Date()
For -10 pervious days
startDate is: Calendar.current.date(byAdding: .day, value: -10, to: Date())!
Note: You can use date from which you want next and previous days date, just change Date(
).
endDate is : Date()
--> (the current date)
So my predicate looks like with a specified time interval.
let predicate = HKQuery.predicateForSamples(
withStart: startDate.beginningOfDay(),
end: endDate,
options: [.strictStartDate,.strictEndDate])
as u can see in my predicate I'm adding beginningOfDay()
method this will allow me to start the date from 00:00
beginningOfDay()
method description :
func beginningOfDay() -> Date {
let beginningOfDay = Calendar.current.startOfDay(for: self)
return beginningOfDay
}
you can also create a predicate format string to create equivalent predicates as describe in heathkitDoc.
let explicitTimeInterval = NSPredicate(format: "%K >= %@ AND %K < %@",
HKPredicateKeyPathEndDate, myStartDate,
HKPredicateKeyPathStartDate, myEndDate)
Hopefully, will do the trick.
Upvotes: 1
Reputation: 16660
A date is simple a number. I've posted a longer explanation for this here.
So a simple number is put into the statement. It is the numerical representation of your date. To treat the number as date, it is casted to the given type "NSDATE"
.
Upvotes: 0