I’m encountering a peculiar issue with the production environment of my CloudKit public database, and was wondering if anyone might have encountered something similar or have suggestions.
I have a CKRecord of type UserInfoRecord with a mostRecentEventDate property.
When I create an NSPredicate to filter for records where mostRecentEventDate is in the past 3 days, I get no records back, even though I expect to have thousands of records that match that query.
However, when I change it to the past 7 days, for example, I do get the expected thousands of records. I was getting some records with 4 and 5 days, but not anymore as more time has passed.
It seems like maybe the CloudKit QUERYABLE index for the mostRecentEventDate on UserInfoRecord is out of date. Does anyone know if there is a way to reset a particular index, or all indexes, or something like that?
I can’t figure out anything else it could be. It seems to apply to all users of all versions I have tested across multiple versions of iOS (15, 16, 17) and multiple physical devices and simulators logged into iCloud (different accounts) and not logged into iCloud.
Here is my relevant code:
// 3 days ago
let maxTimeAgo = Date().addingTimeInterval(60 * 60 * -24 * 3)
// When I use 7 days, it returns some records
// let maxTimeAgo = Date().addingTimeInterval(60 * 60 * -24 * 7)
// Filter for records after maxTimeAgo
let predicate = NSPredicate(format: "%@ < mostRecentEventDate", argumentArray: [maxTimeAgo])
// Create the actual query to request the records from CloudKit
let query = CKQuery(recordType: "UserInfoRecord", predicate: predicate)
// Async fetch all records from CloudKit public DB
// -> records: [CKRecords]
// Sort the records by mostRecentEventDate, newest first
let sortedRecordsArray = records.sorted { (record1, record2) -> Bool in
guard let date1 = record1["mostRecentEventDate"] as? Date else { return false }
guard let date2 = record2["mostRecentEventDate"] as? Date else { return true }
return date1 > date2
}
// I know I can do the sorting with NSSortDescriptor on the query instead of sorting after the fact, but I switched to this during testing to minimize what's happening in the query. Both ways seem to have the issue.
// When I look at the newest mostRecentEventDate from a record, the date is some time in the past day, even though it wasn't picked up in the predicate that covered the last 3 days
if let newestRecord = sortedRecordsArray.first,
let mostRecentEventDate = newestRecord["mostRecentEventDate"] as? Date {
print("Newest mostRecentEventDate:")
print(mostRecentEventDate.formatted(date: .numeric, time: .complete))
}