iOS 实时监听文件夹的变化

1.添加属性

@property (nonatomic, strong)  dispatch_source_t source;

2.开启监听

- (void)startManager {
    [self startMonitorFile];
}
- (void)startMonitorFile {  //监听Document文件夹的变化
    NSURL *directoryURL = [NSURL URLWithString:[SandBoxHelper 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: {
                PVRLog(@"Document目录内容发生变化!!!");
                if (self.isConvenientFinished) {
                    self.isConvenientFinished = NO;
                    [self directoryDidChange];
                }
                break;
            }
            default:
                break;
        }
    });
    dispatch_source_set_cancel_handler(source, ^{
        close(fd);     
    });
    self.source = source;
    dispatch_resume(self.source);
}

3.在退出的时候,注销一下

- (void)stopManager {
    dispatch_cancel(self.source);   
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,973评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,993评论 19 139
  • 2017.02.22 可以练习,每当这个时候,脑袋就犯困,我这脑袋真是神奇呀,一说让你做事情,你就犯困,你可不要太...
    Carden阅读 1,378评论 0 1
  • 久闻东野圭吾大名已久,昨天买了他的一本书。回到寝室便迫不及待的打开阅读,一开始阅读便停不下来,花了一下午的时间便将...
    关家大小姐阅读 513评论 2 2
  • 我也不知道自己怎么了,反正是,喜欢上了。喜欢上一个我叫他看电影他不仅水我而且很淡定的继续玩电脑的傻逼。 我在青春不...
    帅气的张大侠阅读 263评论 0 2