'CloudKit Not Fetching Newly Inserted Records

I am using CloudKit to insert data into the database. The initial fetch works fine but when I add a new record and try to fetch all records again, it ignores the last inserted record. If I run the app again, my newly created record shows up correctly. So, the question is why I am not able to get all the records after inserting a brand new record.

func saveItem(title: String, price: Decimal) {
        
        let record = CKRecord(recordType: RecordType.itemListing.rawValue)
        let itemListing = ItemListing(title: title, price: price)
        record.setValuesForKeys(itemListing.toDictionary())
        
        self.database.save(record) { newRecord, error in
            if let error = error {
                print(error)
            } else {
                // get all items from CloudKit
                self.populateItems()
            }
        }
    }


 func populateItems() {
        
        var items: [ItemListing] = []
        let query = CKQuery(recordType: RecordType.itemListing.rawValue, predicate: NSPredicate(value: true))
       
        database.fetch(withQuery: query) { result in
            switch result {
                case .success(let result):
                    print(result.matchResults)
                     result.matchResults.compactMap { $0.1 }
                     .forEach {
                         switch $0 {
                             case .success(let record):
                                 
                                 if let itemListing = ItemListing.fromRecord(record) {
                                     items.append(itemListing)
                                 }
                                 
                             case .failure(let error):
                                 print(error)
                         }
                         
                     }
                    DispatchQueue.main.async {
                        self.items = items.map(ItemViewModel.init)
                    }
                    
                case .failure(let error):
                    print(error)
            }
        }
    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source