2011-05-09 105 views
3

我正在使用XCode 3.2.5 iOS SDK 4.2为iPad开发应用程序。此应用程序需要打开PDF,DOC和XLS文件并将其预览给用户。UIWebView不打开ms word(doc)和ms excel(xls)文件

我试图用UIWebView控件打开它们。只有PDF文件正在正确打开。打开DOC或XLS时,我看到一个黑色的空白视图。 这在模拟器和设备中发生。

我在做什么错?

下面是代码:

-(void)prepareToShow:(NSString*)filePath fileType:(NSString*)fileType request:(NSURLRequest*)request{ 

UIWebView *webView = (UIWebView*)self.view; 
self.actualFilePath = filePath; 

NSLog(@"File Path %@",filePath); 

NSString *mimeType = @""; 
if ([fileType caseInsensitiveCompare:@"PDF"]==NSOrderedSame){ 
    mimeType = @"application/pdf"; 
} else if ([fileType caseInsensitiveCompare:@"DOC"]==NSOrderedSame){ 
    mimeType = @"application/msword"; 
} else if ([fileType caseInsensitiveCompare:@"XLS"]==NSOrderedSame){ 
    mimeType = @"application/vnd.ms-excel"; 
} 

[webView loadData:[NSData dataWithContentsOfFile:filePath] MIMEType:mimeType textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://www.google.com"]]; 

} 
+0

服务器上的.doc和.xls的mime类型是否设置正确? – onnoweb 2011-05-09 19:51:28

+0

服务器只是发送原始数据。我有一个读取这些数据的函数,并在临时目录中创建文件(根据文件类型)。我已经在模拟器上测试了这个运行。该文件已创建,我可以在Mac上打开它(预览它)。这告诉我该文件已正确创建。 – 2011-05-10 12:42:24

+1

尝试通过UIDocumentController而不是UIWebView打开它们:http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIDocumentInteractionController_class/Reference/Reference.html%23//apple_ref/doc/uid/TP40009304 – onnoweb 2011-05-10 13:57:49

回答

3

对于加载word或excel或pdf文件,你需要的是document filephysical path。这意味着文件应该是saved in document or temporary directory或者它可能在application bundle

//now use file path to load in webview 
[yourWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:yourFilePath]]];