How to monitor a folder for new files in swift?

前端 未结 10 2151
既然无缘
既然无缘 2020-12-23 17:17

How would I monitor a folder for new files in swift, without polling (which is very inefficient)? I\'ve heard of APIs such as kqueue and FSEvents - but I\'m not sure it\'s p

10条回答
  •  没有蜡笔的小新
    2020-12-23 17:54

    I've tried to go with these few lines. So far seems to work.

    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_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
    }
    

    Be sure to not get into retain cycle. If you are going to use owner of this instance in block, do it safely. For example:

    self.directoryObserver = DirectoryObserver(URL: URL, block: { [weak self] in
    
        self?.doSomething()
    })
    

提交回复
热议问题