0

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!

user3745888
  • 6,143
  • 15
  • 48
  • 97
  • I neither see any print command in your code nor the actual values of the dates. Therefore it is hard to say, whether the print out is correct. – Amin Negm-Awad Oct 10 '17 at 01:58

2 Answers2

1

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.

sarra.srairi
  • 150
  • 14
0

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".

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50