watch file for changes in swift

To watch a file for changes in Swift, we can use the FileHandle and NotificationCenter classes.

main.swift
import Foundation

func watchFile(atPath path: String) {
    let fileHandle = FileHandle(forReadingAtPath: path)
    fileHandle?.waitForDataInBackgroundAndNotify()
    
    NotificationCenter.default.addObserver(forName: .NSFileHandleDataAvailable, object: fileHandle, queue: nil) { notification in
        let data = fileHandle?.availableData
        
        // Handle file changes here
        print("Received data:", String(data: data ?? Data(), encoding: .utf8) ?? "")
        
        // Notify the file handle to keep watching for changes
        fileHandle?.waitForDataInBackgroundAndNotify()
    }
}

watchFile(atPath: "/path/to/my/file.txt")
652 chars
19 lines

The above function, watchFile, takes in the file path and sets up a FileHandle to monitor the file. It then waits for data to become available using the waitForDataInBackgroundAndNotify method.

Next, it registers an observer for the .NSFileHandleDataAvailable notification using the addObserver method. When the notification is received, it retrieves the available data from the FileHandle and processes it accordingly. Finally, it calls waitForDataInBackgroundAndNotify again to continue monitoring for changes.

gistlibby LogSnag