JohnSundell / Files

A nicer way to handle files & folders in Swift
MIT License
2.53k stars 182 forks source link

File observer #62

Closed ghost closed 6 years ago

ghost commented 6 years ago

Have you considered extending files with this?

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
    }
}
JohnSundell commented 6 years ago

Haha nice one 😅 However, this sort of functionality is out of scope for this project 🙂