CTCoreAttachment* core_att=(CTCoreAttachment*)sender.tag;
NSString *ext=[core_att.decodedFilenamepathExtension];
NSString* temp=pathForTemporaryFile(ext);
[core_att writeToFile:temp];
// NSLog(@"charset:%@",core_att.charset);
[ self openFile :temp attach :core_att];pathForTemporaryFile()函数用于在tmp文件夹下产生一个随机的临时文件名。然后用CTCoreAttachment的writeToFile:方法进行保存。当然,为了不丢失文件类型,我们必须在临时文件中保留原来的文件扩展名。然后调用openFile:attach:方法在webview中打开附件文件: -( void )openFile:( NSString *)tempFile attach:( CTCoreAttachment *)att{⋯⋯previewVC* vc=[[previewVCalloc]init];
[self.navigationControllerpushViewController:vc animated:YES];
[vc openTemporaryFile:tempFile attach:att];
[vc release ]; }注意webview支持预览的文件相当多,我们用一个plist文件保存了它所支持的一些mime类型。但实际上还不止这么多:<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plistPUBLIC "-//Apple//DTDPLIST 1.0//EN""http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<string>text/plain</string>
<string>text/html</string>
<string>text/xml</string>
<string>image/tiff</string>
<string>image/png</string>
<string>image/x-icon</string>
<string>image/jpeg</string>
<string>image/pict</string>
<string>image/gif</string>
<string>image/bmp</string>
<string>application/pdf</string>
<string>application/msword</string>
<string>application/vnd.ms-excel</string>
<string>text/richtext</string>
</array>
</plist>previewVC中放了一个webview用于预览附件文件,它的openTemporaryFile:attach:方法实现如下:-(void)openTemporaryFile:(NSString *)temp attach:(CTCoreAttachment*)att{
self.title=att.decodedFilename;
NSString* contentType=att.contentType;
if (contentType && [contentType isEqualToString:@"text/plain"]) {
[selfopenTextFile:temp mimeType:contentType];
}else{
[webViewloadRequest:
[NSURLRequestrequestWithURL:
[NSURLfileURLWithPath:temp]]];
}
} 这个方法堆text/plain类型的文件(.txt、.text)进行特别处理。因为这类文件的字符集charset从文件名无法推断。一个.txt文件中的字符编码可能是任意的:utf-8、ascii,如果有中文,那么还可能是gb2312或者gbk的。因此在openTextFile:mimeType:方法中,我们先后尝试了utf-8、gbk和gb2312编码,如果都不正确,则采用us-ascii。最后用推断出的编码加载文件到webview:NSError* error=nil;
NSString* encoding;
// determine text encoding
NSString* content=[NSStringstringWithContentsOfFile:file
encoding:NSUTF8StringEncoding
error:&error];
if (error) {
error=nil;
content=[NSStringstringWithContentsOfFile:file
encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)
error:&error];
if (error) {
error=nil;
// 0x0421 is kCFStringEncodingDOSChineseSimplifdeclared in CFStringEncodingExt.h,
// this hinted the codepage 936 which is gb2312 with a reference from IANA encoding
content=[NSStringstringWithContentsOfFile:file
encoding:CFStringConvertEncodingToNSStringEncoding(0x0421)
error:&error];
if (error)
encoding=@"us-ascii";
else
encoding=@"gb2312";
}else{
encoding=@"GB18030";
}
}else{
encoding=@"UTF-8";
}
[webViewloadData:[NSDatadataWithContentsOfFile:file]
MIMEType :type textEncodingName :encoding baseURL : nil ]; 而且,我们使用了webview的loadData:MIMEType:textEncodingName:baseURL:方法,而不是一般的loadRequest:方法,否则对于中文text/plain文件,显示的是乱码。