How to monitor a folder for new files in swift?

2020-05-14 08:21发布

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 possible to implement them in swift?

标签: macos swift
9条回答
等我变得足够好
2楼-- · 2020-05-14 08:55

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

}
查看更多
够拽才男人
3楼-- · 2020-05-14 08:56

The simplest solution is to use Apple's DirectoryMonitor.swift https://developer.apple.com/library/mac/samplecode/Lister/Listings/ListerKit_DirectoryMonitor_swift.html

var dm = DirectoryMonitor(URL: AppDelegate.applicationDocumentsDirectory)
dm.delegate = self
dm.startMonitoring()
查看更多
放我归山
4楼-- · 2020-05-14 08:57

Easiest method I've found that I'm currently using is this wonderful library: https://github.com/eonist/FileWatcher

From README

Installation:

  • CocoaPods pod "FileWatcher"
  • Carthage github "eonist/FileWatcher" "master"
  • Manual Open FileWatcherExample.xcodeproj
let filewatcher = FileWatcher([NSString(string: "~/Desktop").expandingTildeInPath])

filewatcher.callback = { event in
  print("Something happened here: " + event.path)
}

filewatcher.start() // start monitoring
查看更多
登录 后发表回答