-
Notifications
You must be signed in to change notification settings - Fork 0
/
URLWatcher.swift
34 lines (28 loc) · 954 Bytes
/
URLWatcher.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
import Foundation
extension URL {
var contents: AsyncStream<[String]?>? {
guard let charPath = path.cString(using: .utf8) else {
return nil
}
let descriptor = open(charPath, O_EVTONLY)
guard descriptor != -1 else {
return nil
}
return AsyncStream([String]?.self) { continuation in
let eventSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: descriptor,
eventMask: .all, queue: .main)
eventSource.setCancelHandler {
close(descriptor)
}
continuation.onTermination = { _ in
eventSource.cancel()
}
func yieldContents() {
continuation.yield(try? FileManager.default.contentsOfDirectory(atPath: path))
}
eventSource.setRegistrationHandler(handler: yieldContents)
eventSource.setEventHandler(handler: yieldContents)
eventSource.activate()
}
}
}