Gav*_*avy 6 iphone xcode nsfilemanager ios
您将如何监视目录NSFileManager?
我想在我的应用程序运行时检测何时在我的文档目录中删除/添加了文件。
这是我用Swift用GCD代替Mach并用闭包代替委托编写的DirectoryWatcher版本
import Foundation
@objc public class DirectoryWatcher : NSObject {
override public init() {
super.init()
}
deinit {
stop()
}
public typealias Callback = (_ directoryWatcher: DirectoryWatcher) -> Void
@objc public convenience init(withPath path: String, callback: @escaping Callback) {
self.init() // modified for Swift 3+
if !watch(path: path, callback: callback) {
assert(false)
}
}
private var dirFD : Int32 = -1 {
didSet {
if oldValue != -1 {
close(oldValue)
}
}
}
private var dispatchSource : DispatchSourceFileSystemObject?
@objc public func watch(path: String, callback: @escaping Callback) -> Bool {
// Open the directory
dirFD = open(path, O_EVTONLY)
if dirFD < 0 {
return false
}
// Create and configure a DispatchSource to monitor it
let dispatchSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: dirFD, eventMask: .write, queue: DispatchQueue.main)
dispatchSource.setEventHandler {[unowned self] in
callback(self)
}
dispatchSource.setCancelHandler {[unowned self] in
self.dirFD = -1
}
self.dispatchSource = dispatchSource
// Start monitoring
dispatchSource.resume()
// Success
return true
}
@objc public func stop() {
// Leave if not monitoring
guard let dispatchSource = dispatchSource else {
return
}
// Don't listen to more events
dispatchSource.setEventHandler(handler: nil)
// Cancel the source (this will also close the directory)
dispatchSource.cancel()
self.dispatchSource = nil
}
}
Run Code Online (Sandbox Code Playgroud)
像苹果公司的DirectoryWatcher示例一样使用它,如下所示:
let directoryWatcher = DirectoryWatcher(withPath: "/path/to/the/folder/you/want/to/monitor/", callback: {
print("the folder changed")
})
Run Code Online (Sandbox Code Playgroud)
销毁该对象将停止监视,或者您可以显式停止它
directoryWatcher.stop()
Run Code Online (Sandbox Code Playgroud)
它应该以编写(未测试)的方式与Objective C兼容。使用它会像这样:
DirectoryWatcher *directoryWatcher = [DirectoryWatcher.alloc initWithPath: @"/path/to/the/folder/you/want/to/monitor/" callback: ^(DirectoryWatcher *directoryWatcher) {
NSLog(@"the folder changed")
}];
Run Code Online (Sandbox Code Playgroud)
停止它是相似的
[directoryWatcher stop];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4663 次 |
| 最近记录: |