简体   繁体   中英

How can I get last 10 days from healthkit?

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!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM