2011-05-09 104 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]]];