How to monitor a folder for new files in swift?

前端 未结 10 2131
既然无缘
既然无缘 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:52

    I adapted Stanislav Smida's code to make it work with Xcode 8 and Swift 3

    class DirectoryObserver {
    
        private let fileDescriptor: CInt
        private let source: DispatchSourceProtocol
    
        deinit {
    
          self.source.cancel()
          close(fileDescriptor)
        }
    
        init(URL: URL, block: @escaping ()->Void) {
    
          self.fileDescriptor = open(URL.path, O_EVTONLY)
          self.source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: self.fileDescriptor, eventMask: .all, queue: DispatchQueue.global())
          self.source.setEventHandler { 
              block()
          }
          self.source.resume()
      }
    
    }
    

提交回复
热议问题