ios - 从 WKWebview 从 cordova-ios 的数据目录加载 html 文件

标签 ios cordova wkwebview cordova-ios

我正在开发 cordova-ios 应用程序。我的应用程序将从服务器下载 zip 文件(包含 html 文件 ex:-second_login.html),然后我们将其解压缩到数据目录中。成功解压缩后,应用程序应导航至 second_login.html。应用程序在带有 cordova-ios 5.1.1 的 UIWebview 中运行良好。但它不适用于带有 WKWebview 的 cordova-ios-6.1.0。

使用 cordova-ios-6.1.0,我在数据目录中成功下载并解压到以下路径。

/var/mobile/Containers/Data/Application/<APPID>/Library/NoCloud/<APP_NAME>//files/www-24862240/second_login.html.

为了加载这个 second_login.html,我使用了 document.location = "<PATH_MENTIONED_ABOVE>"

最初,我们在下载 zip 文件时遇到问题(Cookie 同步问题),为此我们使用了 cordova-plugin-ios-xhr插入。然后我们成功下载了 zip 文件。

最佳答案

经过 2 个月的努力,我们找到了解决我的问题的方法。 Native Webkit webview 在 swift 中运行良好。所以我们发现 cordova-ios 正在做一些限制。所以我们在 cordovaLib xcode 项目中添加了一些方法。

  1. 找出 cordovalib xcode 项目中的 WebviewEngine 文件夹。 (cordovaLib.xcodeproj -> 私有(private) -> 插件 -> CDVWebviewEngine)

  2. 在 CDVWebViewEngine.h 文件中 allowsBackForwardNavigationGestures 函数后添加新函数

    - (void)loadFileURL:(CDVInvokedUrlCommand*)command;

3)在CDVWebViewEngine.m文件的defaultResourcePolicyForURL函数之后添加如下函数

-(void)loadFileURL:(CDVInvokedUrlCommand*)command;
{

NSString* fileurlStr = [command argumentAtIndex:0];
NSString* folderurlStr = [command argumentAtIndex:1];
NSURL *nsURLfile = [NSURL fileURLWithPath:fileurlStr];
NSURL *nsURLfileroot = [NSURL fileURLWithPath:folderurlStr];

NSFileManager* fileManager = [NSFileManager defaultManager];
NSArray* contentOfDirectory = [fileManager contentsOfDirectoryAtPath:folderurlStr error:nil];
int contentCount = [contentOfDirectory count];

int i;
for(i=0;i<contentCount;i++){
NSString* fileName = [contentOfDirectory objectAtIndex:i];
NSString* path = [folderurlStr stringByAppendingFormat:@"%@%@",@"/",fileName];
NSLog(path);
}

if ([fileManager fileExistsAtPath:[nsURLfile path]]){
[(WKWebView*)_engineWebView loadFileURL:nsURLfile allowingReadAccessToURL:nsURLfileroot];
}else{
NSLog(@"file does not exist");
}
}
  1. 然后在我们的应用程序 javascript 文件中,使用下面的代码导航到下载的捆绑文件。这里的路径是 zip 下载并解压缩到数据目录位置,具有自定义文件夹名称(在我们的例子中)。

    如果(isIOS()){

              var path = cordova.file.dataDirectory + APP_NAME_FOLDER + "/" + localStorage.zipExtractLocation +"/";
    
                var wkPath = path.replace("file://", "");
    
             cordova.exec( null, null, 'CDVWebViewEngine', 'loadFileURL', [wkPath+"index.html", wkPath] );
    
             }
    
  2. 在 config.xml 中添加以下首选项

<preference name="deployment-target" value="12" />
<preference name="allowFileAccessFromFileURLs" value="true" />

关于ios - 从 WKWebview 从 cordova-ios 的数据目录加载 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64364921/

相关文章:

ios - 有没有办法在 WKWebView 中设置本地存储

ios - 在核心数据中检索/保存自定义对象时出错

ios - 滚动到顶部后未调用 TodayExtension 的 ViewWillAppear

cordova-plugin-whitelist 错误 404 未找到

ios - 手机间隙; iOS 键盘导致框架在每次击键后向上移动

ios - WKWebview 未检测为移动设备

ios - 设置 UITableView 的最大高度

ios - 如何在创建 xcode 项目模板时添加 "Class Prefix"字段

javascript - 在从 Phonegap 相机捕获的图像上绘制文本(自定义文本)

ios - 为什么我的 HTML 字符串在 WebView iOS 中没有显示正确的 html 标签?