监听Documents文件夹内文件发生改变

// 当Documents内文件发生改变时,启动计时器,每秒计算一次大小,当大小不发生改变时说明传输完毕,就开始刷新。
@property (nonatomic, strong) NSTimer             *timer;
// 原Documents内文件大小
@property (nonatomic, assign) NSInteger           filesSize;
// Documents内文件改变后的大小
@property (nonatomic, assign) NSInteger           foundSize;
- (NSTimer *)timer {
    if (!_timer) {
        _timer = [[NSTimer alloc] init];
        [_timer setFireDate:[NSDate distantFuture]];
    }
    return _timer;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    _fileManager = [NSFileManager defaultManager];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(compareSize) userInfo:nil repeats:YES];
    [self.timer setFireDate:[NSDate distantFuture]];

    //** 监听Documents文件夹内的文件是否变化
    int const folderdescriptor = open([kDocumentPath fileSystemRepresentation], O_EVTONLY);
    dispatch_source_t _directorySource = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, folderdescriptor, DISPATCH_VNODE_WRITE, DISPATCH_TARGET_QUEUE_DEFAULT);
    dispatch_source_set_event_handler(_directorySource, ^{
        unsigned long const data = dispatch_source_get_data(_directorySource);
        if (data & DISPATCH_VNODE_WRITE) {
            // Do all the work on the main thread,
            // including timer scheduling, notifications delivering
            dispatch_async(dispatch_get_main_queue(), ^{
                [self directoryDidChanger];
            });
        }
    });
    
    dispatch_source_set_cancel_handler(_directorySource, ^{
        close(folderdescriptor);
    });
    
    dispatch_resume(_directorySource);
}
// 当Documengs文件夹内文件发送改变时
- (void)directoryDidChanger {
    
    _filesSize = [self getSizeOfFilePath:kDocumentPath];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.timer setFireDate:[NSDate date]];
    });
    
}

- (void)dealloc {
    // 移除计时器
    [self.timer invalidate];
}
// 获取所有文件
- (NSArray *)directoryFiles {
    NSArray *files = [_fileManager subpathsAtPath:kDocumentPath];
    return files;
}
// 比较文件大小,以此监听是否还在传输文件
- (void)compareSize {
    _foundSize = [self getSizeOfFilePath:kDocumentPath];
    
    if (_foundSize == _filesSize) { // 如果大小没有再发生改变则刷新数据
        [self.timer setFireDate:[NSDate distantFuture]];
        [self selectDate]; // 开始刷新数据
    }
    
    _filesSize = _foundSize;
}
原文地址:https://www.cnblogs.com/pengyunjing/p/5998805.html