iOS使用NSInputStream加载TXT,RTF等大文件
2021-12-17 本文已影响0人
Z小新
业务场景:
APP内加载大文本文件,例如小说阅读,考试刷题等。直接采用webView或者textView加载会造成严重卡顿。这时候我们就需要引用新的API.我们今天主要研究的就是它。
NSInputStream
直接上代码,代码很简单。
重点!!!!!!!子线程加载数据,主线程刷新UI ,避免频繁刷新
- (void)loadFileContentsIntoTextView{
// 子线程加载 一定要子线程 避免UI卡顿
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// 文件路径
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"txt" ofType:@"txt"];
//通过流打开一个文件
NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath: filePath];
[inputStream open];
NSInteger maxLength = 12800;// 数据分片大小
uint8_t readBuffer [maxLength];
//是否已经到结尾标识
BOOL endOfStreamReached = NO;
// NOTE: this tight loop will block until stream ends
while (! endOfStreamReached)
{
NSInteger bytesRead = [inputStream read: readBuffer maxLength:maxLength];
if (bytesRead == 0)
{//文件读取到最后
endOfStreamReached = YES;
}
else if (bytesRead == -1)
{//文件读取错误
endOfStreamReached = YES;
}
else
{
NSString *readBufferString =[[NSString alloc] initWithBytesNoCopy: readBuffer length: bytesRead encoding: NSUTF8StringEncoding freeWhenDone: NO];
// 主线程刷新
dispatch_sync(dispatch_get_main_queue(), ^{
[self appendTextToView: readBufferString];
});
}
}
[inputStream close];
});
}
// array缓存加载回来的数据
- (void)appendTextToView:(NSString *)str{
// 过滤空置
if (kIsEmptyStr(str)) {
return;
}
if (kIsEmptyArr(self.arrText)) {
self.txtView.text = str;
}
// textView频繁刷新会造成卡顿 ,自己掌握刷新时机
[self.arrText addObject:str];
}