Tag Archives: NSMetadataQuery

How to detect file changes in your ubiquitous iCloud Folder

If Device A saves or changes a file in your app’s iCloud folder, Device B might want to know about this. So you’d imagine there should be an easy way to monitor those changes by way of a notification or a delegate. Sadly there isn’t. Like many things in Objective C, this is way more complicated than it needs to be.

Sure, we could use UIDocument which has those notifications built in – but that adds a layer of complexity to the simple act of saving a frigging file that many apps seriously don’t need.

The good news is that we can monitor file changes to any file in our ubiquitous folder by executing an NSMetadataQuery. It feels like a hack but it works. Let me explain.

An NSMetadataQuery is really a way to search files in a folder and return results. This includes iCloud documents. As a byproduct it sends notifications if there have been changes to those results since the last query. Queries are ongoing until stopped and are carried out once every second.

So to monitor changes to files in our iCloud folder, we need to do the following:

  • create an NSMetadataQuery, monitoring all files in our ubiquitous Documents folder (including new save, overwrite and delete)
  • add an observer for the query
  • create a method that gets fired via the observer

Let’s do this