Search code examples
iosswiftios8nspredicatecloudkit

Using "timeIntervalSinceNow" in a predicate in SWIFT


I am trying to query for records that are created in the last 1 hour using Cloudkit (in SWIFT)

I have tried:

let predicate = NSPredicate(predicateWithFormat : "timeIntervalSinceNow %@ < %f", "creationTime", -3600)

without success. The error message refers to a parsing error.

Anyone has a clue what would be the right format?

n.b creationTime is the name of the field in the Table


Solution

  • Your predicate isn't valid. Take a look at Apple's guide for creating NSPredicates.

    You should use a key path on the left hand side of the expression. I assume that you have an array of objects, and these objects have a property named creationTime. Then the predicate should look like this:

    NSPredicate(format: "creationTime.timeIntervalSinceNow > %d", -3600)
    

    Note that I have used "greater than" > operator instead of < in the predicate you posted. That's because a date from the past will return a negative value from timeIntervalSinceNow method, as documentation states.

    EDIT: Seems you can't use key paths in CloudKit predicates. But I think you can create a reference date (an hour ago) and use it for comparison predicate:

    let now = NSDate()
    if let anHourAgo = NSCalendar.currentCalendar().dateByAddingUnit(
        .HourCalendarUnit,
        value: -1,
        toDate: now,
        options: NSCalendarOptions(0)) {
            let predicate = NSPredicate(format: "creationDate > %@", anHourAgo)
            let filtered = records.filteredArrayUsingPredicate(predicate!)
    }