14

I want to fetch the last X minutes of public/private entries from CloudKit.

I tried something in this effect but failed:

    let date = NSDate(timeInterval: -60.0 * 120, sinceDate: NSDate())
    let predicate = NSPredicate(format: "creationDate > %@", date)

But this will get me data, but I'm not sure if I'm querying everything or just to some kind of cap:

    let predicate = NSPredicate(value: true)

I want to be able to query by certain amount of time. Is this possible without doing the creation sorting logic on the client side?

Here's the complete code block:

func fetchPublicData(completion: ((records:[AnyObject]) -> Void)!)
{
    let date = NSDate(timeInterval: -60.0 * 120, sinceDate: NSDate())
    let predicate = NSPredicate(format: "creationDate > %@", date)
    let query = CKQuery(recordType: "MyDataRecordType", predicate: predicate)

    let container = CKContainer.defaultContainer()
    let publicDb = container.publicCloudDatabase

    publicDb.performQuery(query, inZoneWithID: nil,
    {
        (results, error) in

        if error != nil
        {
            self.handleError(error)
        }
        else
        {
            // do stuff
        }
    })
}

Thanks.

Genki
  • 3,055
  • 2
  • 29
  • 42
  • 1
    aside: `Date(timeIntervalSinceNow: -60 * 120)` is another way to create the date you're using - "120 minutes ago" – bshirley Jul 13 '17 at 19:29

1 Answers1

26

UPDATE 10/5/2020:

Found out my own question. You'll need to log in to CloudKit dashboard, go to Schema and make sure "Index Type" is set to queryable.

enter image description here

Here's more detailed document of what kind of NSPredicate you can use for CloudKit: https://developer.apple.com/documentation/cloudkit/ckquery#//apple_ref/doc/uid/TP40014043-CH1-SW8

Once setup, you'll be able to query by date like so:

let date = NSDate(timeInterval: -60.0 * 120, sinceDate: NSDate())
let predicate = NSPredicate(format: "creationDate > %@", date)

[DEPRECATED] Screenshot of CloudKit dashboard for first accepted answer below:

enter image description here

Genki
  • 3,055
  • 2
  • 29
  • 42
  • Thanks, I promise I won't use this to poll CloudKit on a timer for modificationDate to avoid setting up all those nasty zone callbacks. – Dan Rosenstark Apr 09 '17 at 23:20
  • @Genki: I'm afraid with the new CloudKit Dashboard I no longer find how to activate the checkmarks… could you help with a new screenshot? – DrMickeyLauer Oct 05 '20 at 16:54
  • 1
    @DrMickeyLauer - Thanks for calling that out. I updated it. – Genki Oct 05 '20 at 17:22