A class to watch one or more directories, and post notifications when changes occur to their contents
TIKQDirectoryWatcher is offered under the MIT license. See the
LICENSE file for full details.
TIKQDirectoryWatcher makes use of
kqueues to post notifications when changes occur to the contents of one or more specified directories.
.m files to your project, and create an instance:
TIKQDirectoryWatcher *directoryWatcher = [[TIKQDirectoryWatcher alloc] init];
Add one or more directories to watch:
BOOL success = [directoryWatcher watchDirectory:[@"~/Documents" stringByExpandingTildeInPath] error:nil];
This method will return
NO if the watcher can't find the specified directory, or if any other error occurs. At the moment, the
NSError object is ignored, but will be configured soon. For now, errors are simply logged to the console.
Finally, you'll need to schedule the watcher on the run loop:
success = [directoryWatcher scheduleWatcherOnMainRunLoop:&anyError];
You'll need to register to receive
kTIKQDirectoryWatcherObservedDirectoryActivityNotification notifications when changes occur:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationHandlerMethod:) name:kTIKQDirectoryWatcherObservedDirectoryActivityNotification object:directoryWatcher];
The notification's user info dictionary contains two entries:
kTIKQDirectoryspecifies the name of the directory using a tilde (~) if appropriate, such as
kTIKQExpandedDirectoryspecifies the full name of the directory, such as
Both a sample Mac application and a sample iOS project are included.
If you do not use Dropbox, you'll need to modify the Mac application observed directories to exclude the
~/Dropbox, otherwise you'll see an error in the console when the application tries to watch that directory. The observed directories are specified in the
startWatching: method in
To test for notifications, add or remove a file at the root level of
The iOS example checks for changes made in the application's
/tmp directories. Click the relevant button to add new files to these locations, and trigger the notifications as long as the watcher is enabled.
The Info.plist has
UIFileSharingEnabled set to
YES. When running on a device (iOS 3.2/4 or higher), try adding a file to the application's
/Documents directory using the File Sharing option under the device's Apps tab in iTunes.
Some portions of this code are based on Chapter 15, kqueues, of Advanced Mac OS X Programming (Second Edition) by Mark Dalrymple and Aaron Hillegass.
To Do List
- Fill out
NSErrorobjects if errors occur
- Check for memory leaks if errors occur