2012-04-03 69 views
2

我正在爲iOS構建PhoneGap 1.5(Cordova)應用程序,並希望使用ChildBrowser插件來顯示PDF文件。我已經能夠設置它,並且在查看外部PDF文件(http,https)時它工作得很好。PhoneGap 1.5 ChildBrowser無法顯示本地文件

該應用的離線功能有限。我正在使用文件系統和文件傳輸API來下載PDF文件並將其保存到本地文件系統。當我嘗試使用ChildBrowser插件查看這些文檔時,它們從不加載。

我通過在插件的命令和viewcontroller中添加一些斷點來完成一些故障排除。我發現,當我嘗試查看本地文檔,我打webViewDidFailLoadWithError方法有以下消息:

The operation couldn't be completed. 
(WebKitErrorDomain error 101.) 

控制檯顯示的文件:我試圖加載的文件// URL,如果我瀏覽的在模擬器的safari中的URL,我可以查看文檔。在模擬器中運行時的URL與此類似:

file://localhost/Users/{username}/Library/Application Support/iPhone Simulator/5.1/Applications/5D8EDAB7-4BB7-409E-989D-250A84B37877/Documents/{filename} 

是我在做什麼可能的,如果是這樣,我怎麼需要配置我的應用程序,以便能夠從本地文件顯示PDF文件系統在ChildBrowser?

回答

4

我能夠自己解決這個問題。在PhoneGap的fileEntry.toURI()方法返回一個URL的東西像什麼,我包括在我原來的職位:

file://localhost/Users/{username}/Library/Application Support/iPhone Simulator/5.1/Applications/5D8EDAB7-4BB7-409E-989D-250A84B37877/Documents/{filename} 

通過一些跳鐵圈,以確保文件的URL中逃了出來,相對於應用程序的文件目錄後,所產生的加載成功的URL看起來像這樣:

file:///Users/{username}/Library/Application%20Support/iPhone%20Simulator/5.1/Applications/B50682DD-AE6C-4015-AE61-3879576A4CB7/Documents/{relativeUri} 

只是有點不同。爲了解決這個問題,也許不是每一種情況,但至少對我來說,我修改了ChildBrowserViewController中的loadURL方法來查找一個文件的URL並去掉絕對的東西,留下一個相對於應用程序文檔目錄的URL。然後我使用NSFileManager來幫助建立一個可以工作的URL。我對iOS開發相對比較陌生,所以也許有更好的方法來做到這一點。歡迎輸入。代碼如下:

- (void)loadURL:(NSString*)url { 
... 
    else if([url hasPrefix:@"file://"]) { 
     NSError *error = NULL; 

     //Create the regular expression to match against 
     NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"file://.*/Documents/" options:NSRegularExpressionCaseInsensitive error:&error]; 

     // Create the new string by replacing the matching of the regex pattern with the template pattern(empty string) 
     NSString *relativeUri = [regex stringByReplacingMatchesInString:url options:0 range:NSMakeRange(0, [url length]) withTemplate:@""]; 
     NSLog(@"New string: %@", relativeUri); 

     NSURL *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 
     NSURL *url = [documentsDirectory URLByAppendingPathComponent:relativeUri]; 
     NSLog(@"New string: %@", url); 
     NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
     [webView loadRequest:request]; 
    } 
... 
}