Created
April 9, 2016 07:50
-
-
Save eonist/a283032a0a0e6c4f8d680cfc5dfb4718 to your computer and use it in GitHub Desktop.
Researching file watching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DirectoryObserver { | |
deinit { | |
dispatch_source_cancel(source) | |
close(fileDescriptor) | |
} | |
init(URL: NSURL, block: dispatch_block_t) { | |
fileDescriptor = open(URL.path!, O_EVTONLY) | |
source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE,UInt(fileDescriptor),DISPATCH_VNODE_WRITE,dispatch_get_main_queue()) | |
//source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, UInt(fileDescriptor), DISPATCH_VNODE_WRITE, dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)) | |
dispatch_source_set_event_handler(source, { dispatch_async(dispatch_get_main_queue(), block) }) | |
dispatch_resume(source) | |
} | |
// | |
private let fileDescriptor: CInt | |
private let source: dispatch_source_t | |
} | |
/* | |
self.directoryObserver = DirectoryObserver(URL: theURL, block: { [weak self] in | |
Swift.print("change: " + "\(self)") | |
//self?.doSomething() | |
}) | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FolderMonitor { | |
enum State { | |
case On, Off | |
} | |
private let source: dispatch_source_t | |
private let descriptor: CInt | |
private let qq: dispatch_queue_t = dispatch_get_main_queue() | |
private var state: State = .Off | |
/// Creates a folder monitor object with monitoring enabled. | |
public init(url: NSURL, handler: ()->Void) { | |
state = .Off | |
descriptor = open(url.fileSystemRepresentation, O_EVTONLY) | |
source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE,UInt(descriptor),DISPATCH_VNODE_WRITE,qq) | |
dispatch_source_set_event_handler(source, handler) | |
start() | |
} | |
/// Starts sending notifications if currently stopped | |
public func start() { | |
if state == .Off { | |
state = .On | |
dispatch_resume(source) | |
} | |
} | |
/// Stops sending notifications if currently enabled | |
public func stop() { | |
if state == .On { | |
state = .Off | |
dispatch_suspend(source) | |
} | |
} | |
deinit { | |
close(descriptor) | |
dispatch_source_cancel(source) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment