Search code examples
ioscloudkit

CloudKit design advice


Let me preface by saying I know the pros and cons of using CloudKit and that I am trying to work around one of these issues. However since Cloudkit is more or less free, thats what I'm using. I am aware this might be easier with a different framework.

For simplicity sake lets say I'm making a social media image sharing app, I want to track photo likes and my framework is CloudKit. I'm trying to figure out the most efficient way to track likes for publicly shared photos.

A few of the options I've mulled over:

  1. Every like is a new record in the public database with a back reference to the photo. Since CK has no aggregate queries, in order to display the number of likes for a photo I need to query all the records for a given reference and count them. If this number gets very large then I'm iterating over the cursor. This seems quick and accurate to write but potentially pretty slow to display a lot of photos.

  2. Likes are individual records in the private database, I update the aggregate in a single record per photo the public db at the same time. Getting the total like count is now a one record query. Determining if a user has already liked something also becomes easier with a smaller private db of likes. The route sounds like the fastest but its is potentially inaccurate if multiple users are liking the same photo. Also deleting a user and all their private likes leaves my aggregates unchanged, I'd need some process updating the aggregates.

I'd love any advice I can get, thanks !


Solution

  • You second approach is the best, and it's accurate. When you read a data, change it and save it, CloudKit will check if the data is changed in the mean time. So when 2 are updating 1 photo at the same time, then one will get a CloudKit error that the data has changed. Then just try to update again until you succeed.

    No matter what solution you choose, if you want to update the likes after a user is removed, you need a process that does this.