let observer = try FileObserver(file: file)
observer.start {
print("File was changed")
}
Some guy called @JohnSundell wrote this as a blog post 😜 #SwiftBySundell
class FileObserver {
private let file: File
private let queue: DispatchQueue
private var source: DispatchSourceFileSystemObject?
init(file: File) {
self.file = file
self.queue = DispatchQueue(label: "com.myapp.fileObserving")
}
func start(closure: @escaping () -> Void) {
// We can only convert an NSString into a file system representation
let path = (file.path as NSString)
let fileSystemRepresentation = path.fileSystemRepresentation
// Obtain a descriptor from the file system
let fileDescriptor = open(fileSystemRepresentation, O_EVTONLY)
// Create our dispatch source
let source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fileDescriptor,
eventMask: .write,
queue: queue)
// Assign the closure to it, and resume it to start observing
source.setEventHandler(handler: closure)
source.resume()
self.source = source
}
}
Have you considered extending files with this?
Some guy called @JohnSundell wrote this as a blog post 😜 #SwiftBySundell