【问题标题】:PhoneGap 1.5 ChildBrowser can't show local filePhoneGap 1.5 ChildBrowser 无法显示本地文件
【发布时间】:2012-04-07 07:06:36
【问题描述】:

我正在为 iOS 构建一个 PhoneGap 1.5 (Cordova) 应用程序,并希望使用 ChildBrowser 插件来显示 PDF 文件。我已经能够对其进行设置,并且在查看外部 PDF 文件(http、https)时效果很好。

该应用的离线功能有限。我正在使用文件系统和文件传输 API 下载 PDF 文件并将它们保存到本地文件系统。当我尝试使用 ChildBrowser 插件查看这些文档时,它们永远不会加载。

我通过在插件的命令和视图控制器中添加一些断点进行了一些故障排除。我发现当我尝试查看本地文档时,我点击了 webViewDidFailLoadWithError 方法并显示以下消息:

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

控制台显示我尝试加载的文档的 file:// URL,如果我在模拟器上的 safari 中浏览该 URL,我可以查看该文档。在模拟器中运行时的URL是这样的:

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

我正在做的事情是否可行?如果可以,我需要如何配置我的应用程序才能在 ChildBrowser 中显示本地文件系统中的 PDF 文件?

【问题讨论】:

    标签: cordova phonegap-plugins childbrowser


    【解决方案1】:

    我自己解决了这个问题。 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];
        }
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-06
      相关资源
      最近更新 更多