forked from MartinJNash/SwiftFolderMonitor
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFolderMonitor.swift
49 lines (38 loc) · 1.26 KB
/
FolderMonitor.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import Foundation
open class FolderMonitor {
enum State {
case on, off
}
fileprivate let source: DispatchSource
fileprivate let descriptor: CInt
fileprivate let qq: DispatchQueue = DispatchQueue.main
fileprivate var state: State = .off
/// Creates a folder monitor object with monitoring enabled.
public init(url: URL, handler: @escaping ()->Void) {
state = .off
descriptor = open((url as NSURL).fileSystemRepresentation, O_EVTONLY)
source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: descriptor, eventMask: DispatchSource.FileSystemEvent.write, queue: qq) /*Migrator FIXME: Use DispatchSourceFileSystemObject to avoid the cast*/ as! DispatchSource
source.setEventHandler {
handler()
}
start()
}
/// Starts sending notifications if currently stopped
open func start() {
if state == .off {
state = .on
source.resume()
}
}
/// Stops sending notifications if currently enabled
open func stop() {
if state == .on {
state = .off
source.suspend()
}
}
deinit {
close(descriptor)
source.cancel()
}
}