views:

409

answers:

5

What is the best way to listen to a folder or file to see if it has been saved or if a new file has been added?

A: 

Not sure what's the best way, but A way would be to fire up an NSThread that would regularly (for instance every second) check the creation dates of the files in the directory, and then have a delegate associated with that thread to perform some action when a new file has been added

niklassaers
That's polling and is discouraged. Use FSEvents or kqueues instead, which are APIs designed expressly for this purpose.
Rob Keniger
+5  A: 

Try using FSEvents, although it is a C API

OS 10.5 or newer

cobbal
+1  A: 

If you are changing a file or folder, I believe the Spotlight search engine will update its database to reflect your changes.

So you might set up a thread that listens for kMDQueryDidUpdateNotification notifications through a Spotlight query specific to that file or folder.

When you get those notifications, you could fire a selector that does something you want.

Alex Reynolds
This is a good idea, but the problem with Spotlight is that not all volumes support it (many network volumes in particular) and users also have a habit of turning it off.
Rob Keniger
These are good points. Just thinking out loud.
Alex Reynolds
+13  A: 

The FSEvents API is ideal if you just want to watch directories but it doesn't handle the monitoring of individual files. Stu Connolly has a great Objective-C wrapper for the FSEvents C API, it's called SCEvents and you can get it here:

http://stuconnolly.com/blog/scevents-011/

The nice thing about FSEvents is that you just need to watch one folder and you will be notified of any changes that occur anywhere in the subfolder hierarchy of that folder.

If you need file-level notifications you will need to use kqueues. Uli Kusterer has a great Objective-C wrapper:

http://zathras.de/angelweb/sourcecode.htm#UKKQueue

Either of these methods is a lot easier than wrangling with the C APIs directly, which are not particularly well documented and a bit obtuse.

If you need to support Tiger you'll need to use kqueues as the FSEvents API wasn't officially available in 10.4.

Rob Keniger
+1  A: 

If you do need to use kqueue (as discussed in other answers) Google Toolbox for Mac has a nice Objective-C wrapper that I've used with no issues thus far.

Lawrence Johnston