iOS 实时监听沙盒文件夹的变化

OC 版本

  • 添加属性
@property (nonatomic, strong)  dispatch_source_t source;
  • 开启监听
- (void)startMonitorFile {  //监听Document文件夹的变化
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSURL *directoryURL = [NSURL URLWithString:docPath]; //添加需要监听的目录
    int const fd =
    open([[directoryURL path] fileSystemRepresentation], O_EVTONLY);
    if (fd < 0) {
        NSLog(@"Unable to open the path = %@", [directoryURL path]);
        return;
    }
    dispatch_source_t source =
    dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, fd,
                           DISPATCH_VNODE_WRITE,
                           DISPATCH_TARGET_QUEUE_DEFAULT);
    dispatch_source_set_event_handler(source, ^() {
        unsigned long const type = dispatch_source_get_data(source);
        switch (type) {
            case DISPATCH_VNODE_WRITE:
                NSLog(@"Document file changed");
                break;

            default:
                NSLog(@"Document file changed");
                break;
        }
    });
    dispatch_source_set_cancel_handler(source, ^{
        close(fd);
    });
    self.source = source;
    dispatch_resume(self.source);
}

  • 结束监听
- (void)stopMonitorFile {
    dispatch_cancel(self.source);   
}

Swift 版本

  • 添加属性
fileprivate var sourceTimer: DispatchSourceFileSystemObject!

fileprivate let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!

  • 开启监听
 // MARK: - 监听文件夹变化
    func startMonitorFile() {
        let directoryURL = URL(fileURLWithPath: docPath)
        
        let content:[CChar] = directoryURL.path.cString(using: .utf8)!
        let fd =  open(content, O_EVTONLY)
        if fd < 0 {
            DDLogDebug("Unable to open the path = \(directoryURL.path)")
            return
        }

        let timer = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: .write, queue: DispatchQueue.global())
        timer.setEventHandler {[weak self] in
            let event:DispatchSource.FileSystemEvent = timer.data
            switch event {
            
            case .write:
                DDLogDebug("Document file changed")
            default:
                DDLogDebug("Document file changed")
            }
            
            DispatchQueue.main.async {
                self?.listTb.reloadData()
            }
            
        }

        timer.setCancelHandler {
            DDLogDebug("destroy timer")
            close(fd)
        }
        
        sourceTimer = timer
        timer.resume()
        
    }

  • 结束监听

 func stopMonitorFile() {
        sourceTimer.cancel()
    }

你可能感兴趣的:(iOS 实时监听沙盒文件夹的变化)