NSFileManager监视目录

时间:2011-10-23 17:54:46

标签: iphone ios xcode nsfilemanager

如何使用NSFileManager监视目录。

我希望能够在我的应用程序运行时检测文件目录中删除/添加文件的时间。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

在Apple文档中查找内核队列:文件系统事件的替代方法。 AVPlayerDemo中有 iOS 示例(外观DirectoryWatcher类)。

另外,请查看Directory Monitor博文。

答案 1 :(得分:3)

这是我用Swift编写的DirectoryWatcher版本,使用GCD代替Mach并使用闭包代替委托

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) {
        init()
        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
    }
}

像Apple的DirectoryWatcher示例一样使用它,如下所示:

let directoryWatcher = DirectoryWatcher(withPath: "/path/to/the/folder/you/want/to/monitor/", callback: {
    print("the folder changed")
})

销毁对象将停止观看,或者您可以明确停止

directoryWatcher.stop()

它应该与Objective C的编写方式(未经测试)兼容。使用它就像这样:

DirectoryWatcher *directoryWatcher = [DirectoryWatcher.alloc initWithPath: @"/path/to/the/folder/you/want/to/monitor/" callback: ^(DirectoryWatcher *directoryWatcher) {
    NSLog(@"the folder changed")
}];

停止它是类似的

[directoryWatcher stop];