主要代碼:
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index { //處理txt格式內容顯示有亂碼的情況 NSData *fileData = [NSData dataWithContentsOfFile:self.files]; //判斷是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.files atomically:YES]; } else if(isANSI){ NSData *data = [isANSI dataUsingEncoding:NSUTF16StringEncoding]; [data writeToFile:self.files atomically:YES]; } return [NSURL fileURLWithPath:self.files]; }