import <QuickLook/QuickLook.h>
QLPreviewControllerDelegate,QLPreviewControllerDataSource
-
(void)addQLPreviewVC {
QLPreviewController *QLPreviewVC = [[QLPreviewController alloc] init];
QLPreviewVC.view.frame = self.view.bounds;
QLPreviewVC.dataSource = self;
QLPreviewVC.delegate = self;
if([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
[self addChildViewController:QLPreviewVC];QLPreviewVC.currentPreviewItemIndex = 0;
}
[self.view addSubview:QLPreviewVC.view];
} (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
return 1;
}-
(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
//根据文件名判断文件类型
NSRange pointRange = [self.fileName rangeOfString:@"."];
NSString *subName;
if (pointRange.location>0 && pointRange.location < self.fileName.length-2) {
subName = [self.fileName substringFromIndex:pointRange.location+1];
}
if (subName.length > 3 && [subName containsString:@"#"]) {
subName = [subName substringToIndex:3];
}
if ([subName isEqualToString:@"txt"]&&[[UIDevice currentDevice].systemVersion floatValue] < 9.0) {//使用QLPreviewController展示TXT等文档时,Windows下生成的UTF-8格式的文件会出现中文(以及其他特殊字符)乱码的问题。QLPreviewController只有在UTF16的编码下才能正确显示中文,需要在展示文件之前将文件的编码改为UTF16 //需针对ANSI编码和Unicode编码分别进行解码 //处理txt格式内容显示有乱码的情况 NSData *fileData = [NSData dataWithContentsOfFile:self.filePath]; //判断编码如果已经是NSUTF16StringEncoding编码,则isUNICODE与isANSI为空。 //判断是UNICODE编码 NSString *isUNICODE = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding]; //还是ANSI编码(-2147483623,-2147482591,-2147482062,-2147481296)encoding 任选一个就可以了。 NSString *isANSI = [[NSString alloc] initWithData:fileData encoding:-2147483623]; if (isUNICODE) { NSString *retStr = [[NSString alloc]initWithCString:[isUNICODE UTF8String] encoding:NSUTF8StringEncoding]; NSData *data = [retStr dataUsingEncoding:NSUTF16StringEncoding]; [data writeToFile:self.filePath atomically:YES]; } else if(isANSI){ NSData *data = [isANSI dataUsingEncoding:NSUTF16StringEncoding]; [data writeToFile:self.filePath atomically:YES]; }
}
return [NSURL fileURLWithPath:self.filePath];
}
/*
- 这个方法可不实现
*/
- (void)previewControllerWillDismiss:(QLPreviewController *)controller {
}