如何使用文件系统事件OSX检测更改

时间:2018-06-21 12:19:57

标签: swift macos filesystems

我试图在Mac OS X高山脉中监视文件夹(或测试场景中的文件),然后在目录更改时通知用户。为此,我正在使用FSEventStreamCreate。 下面的代码:

class FileWatch {
       public init(paths: [String], runLoop: RunLoop, latency:CFTimeInterval, 
       eventHandler: @escaping EventHandler) throws {

          self.eventHandler = eventHandler
          // creating context

          var ctx = FSEventStreamContext(version: 0, info: 
          UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()), retain: nil, release: nil, copyDescription: nil)
          //creating the stream    

          guard let eventStream = FSEventStreamCreate(kCFAllocatorDefault,streamCallback, &ctx, paths as CFArray, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), latency, UInt32(kFSEventStreamCreateFlagFileEvents|kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagNoDefer) ) else {
           throw Error.streamCreateFailed
          }
          // running the event stream

          FSEventStreamScheduleWithRunLoop(eventStream, runLoop.getCFRunLoop(), CFRunLoopMode.defaultMode.rawValue)
          if !FSEventStreamStart(eventStream) {
            throw Error.startFailed
          }
          self.eventStream = eventStream
      } 
   }

回调函数:

fileprivate func streamCallback (streamRef: ConstFSEventStreamRef, clientCallBackInfo: UnsafeMutableRawPointer?, numEvents: Int, eventPaths: UnsafeMutableRawPointer, eventFlags: UnsafePointer<FSEventStreamEventFlags>, eventIds: UnsafePointer<FSEventStreamEventId>) {
    print("event flasgs \(eventFlags)")

    let `self` = unsafeBitCast(clientCallBackInfo, to: FileWatch.self)

    guard let eventPathArray = unsafeBitCast(eventPaths, to: NSArray.self) as? [String] else {
       return
   }
     var eventFlagArray = Array(UnsafeBufferPointer(start: eventFlags, count: numEvents))

     var eventIdArray = Array(UnsafeBufferPointer(start: eventIds, count: numEvents))
     print("item flags \(eventFlagArray)")

     for i in 0..<numEvents {
       let path = eventPathArray[i]
       let flag = eventFlagArray[i]
       let eventID = eventIdArray[i]
     } 
 }

例如,当我尝试将文件移至垃圾箱(或其他目录)时,如果我正在路径 /Users/user/Documents/workingDir/About.txt 处观看文件我得到标志67584,它是 kFSEventStreamEventFlagItemRenamed,kFSEventStreamEventFlagItemIsFile ,当我将文件添加到文件夹或重命名文件时,我也得到相同的值。

修改文件时,得到标志1148928 [“ kFSEventStreamEventFlagItemRenamed”,“ kFSEventStreamEventFlagItemIsFile”,“ kFSEventStreamEventFlagItemIsHardlink”,“ kFSEventStreamEventFlagItemXattrMod”]

该如何识别正确的事件?就像文件已被更改,重命名,删除,创建等。

0 个答案:

没有答案