Skip to content

Instantly share code, notes, and snippets.

Last active August 3, 2021 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sidraval/86f3de0b57472cea7b7ecfd957427ee5 to your computer and use it in GitHub Desktop.
Save sidraval/86f3de0b57472cea7b7ecfd957427ee5 to your computer and use it in GitHub Desktop.
FileWatcher / FileListener
import Foundation
fileprivate let queue = DispatchQueue(label: "FileMonitorQueue", target: .main)
enum FileWatcherError: Error {
case directoryOpenFailed(Int32)
case directoryURLInvalid(URL)
final class FileWatcher {
let fsSource: DispatchSourceFileSystemObject
var readSource: DispatchSourceRead!
init(in directory: URL, filename: String, errorHandler: ((Error) -> Void)?) throws {
let fileDescriptor: Int32 = try directory.withUnsafeFileSystemRepresentation { path in
guard let path = path else { throw FileWatcherError.directoryURLInvalid(directory) }
let result = open(path, O_EVTONLY)
guard result >= 0 else { throw FileWatcherError.directoryOpenFailed(errno) }
return result
fsSource = DispatchSource.makeFileSystemObjectSource(
fileDescriptor: fileDescriptor,
eventMask: .write,
queue: queue
fsSource.setEventHandler { [unowned self] in
do {
let fileHandle = try FileHandle(
forReadingFrom: directory.appendingPathComponent(filename)
self.readSource = DispatchSource.makeReadSource(fileDescriptor: fileHandle.fileDescriptor, queue: queue)
self.readSource.setEventHandler {
self.readSource.setCancelHandler {
} catch {
fsSource.setCancelHandler {
deinit {
final class FileListener {
init() {
selector: #selector(handler),
name: .NSFileHandleReadToEndOfFileCompletion,
object: nil
@objc func handler() {
/* file is available for reading here */
Copy link

DevyV commented Feb 19, 2020

Hello Sid,

I am just now learning Swift 5 on macOS 10.14.6 with Xcode 11.3.1.

I would like to create a simple GUI app that monitors a file for changes (e.g. "/Uers/Devy/Documents/test.txt").
I found this code of yours, but being a beginner in Swift coding, I just do not know how to use in a Cocoa app.
I have a Label on the GUI and I wish to update the label whenever the file is changed with the text from the file.

So far, I coded this, however, right here I do not know what to put as "errorHandler":

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        var fw: FileWatcher
        fw = FileWatcher(in: URL(fileURLWithPath: "/Users/Devy/Documents/", isDirectory: true), filename: "test.txt", errorHandler: <???>)        

And I do not know how to read from the file and show the content on the GUI...

Would you be so kind and help me achieve this, please?
Many thanks in advance!

Copy link

@DevyV Not sure if you've seen it, but I wrote an accompanying blog post that might be helpful

errorHandler is an optional callback function that handles any errors that might occur during file reading.

You'll want to listen to notifications for .NSFileHandleReadToEndOfFileCompletion, and update your label in the notification handler function. Line 62 shows an example class that calls the handler function when it receives a notification.

Copy link

DevyV commented May 6, 2020

Hello Sid,

Thanks for your help, I managed to make it work :)

Actually, I am facing a strange issue now:
as long as the monitored file is being edited and saved by a text editor (e.g. SubEthaEdit) Filewatcher can detect changes.
But when I change the contents of the monitored file with AppleScript (see example below) then Filewatcher does NOT detect the change.

Why? Do you have any idea how to fix it?

Here is my AppleScript used to change the contents of the file:

set documentsPath to POSIX path of (path to documents folder from user domain)
set my_file to (documentsPath & "test_file.txt")
set newContent to "new text"

set fileHandle to open for access my_file with write permission
set eof of fileHandle to 0 -- make sure to overwrite the whole contents in the file
write ((newContent as string) & return) to fileHandle --- starting at eof
close access fileHandle

Copy link

DevyV commented May 6, 2020


I solved it myself :)
I needed to change line 26 from:

eventMask: .write,


eventMask: .all,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment