1. ios9以前版本读取本地HTML的问题

当使用loadRequest来读取本地的HTML时,WKWebView是无法读取成功的,后台会出现如下的提示:
Could not create a sandbox extension for /
原因是WKWebView是不允许通过loadRequest的方法来加载本地根目录的HTML文件
而在iOS9的SDK中加入了以下方法来加载本地的HTML文件:
[WKWebView loadFileURL:allowingReadAccessToURL:]
但是在iOS9以下的版本是没提供这个便利的方法的。以下为解决方案的思路,就是在iOS9以下版本时,先将本地HTML文件的数据copy到tmp目录中,然后再使用loadRequest来加载。但是如果在HTML中加入了其他资源文件,例如js,css,image等必须一同copy到temp中。这个是最蛋疼的事情了。

解决方法如下

1.Objective-C:

//将文件copy到tmp目录
- (NSURL *)fileURLForBuggyWKWebView8:(NSURL *)fileURL {
NSError *error = nil;
if (!fileURL.fileURL || ![fileURL checkResourceIsReachableAndReturnError:&error]) {
return nil;
}
// Create "/temp/www" directory
NSFileManager *fileManager= [NSFileManager defaultManager];
NSURL *temDirURL = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:@"www"];
[fileManager createDirectoryAtURL:temDirURL withIntermediateDirectories:YES attributes:nil error:&error]; NSURL *dstURL = [temDirURL URLByAppendingPathComponent:fileURL.lastPathComponent];
// Now copy given file to the temp directory
[fileManager removeItemAtURL:dstURL error:&error];
[fileManager copyItemAtURL:fileURL toURL:dstURL error:&error];
// Files in "/temp/www" load flawlesly :)
return dstURL;
} //调用逻辑
NSString *path = [[NSBundle mainBundle] pathForResource:@"indexoff" ofType:@"html"];
if(path){
if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
// iOS9. One year later things are OK.
NSURL *fileURL = [NSURL fileURLWithPath:path];
[self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
} else {
// iOS8. Things can be workaround-ed
// Brave people can do just this
// fileURL = try! pathForBuggyWKWebView8(fileURL)
// webView.loadRequest(NSURLRequest(URL: fileURL)) NSURL *fileURL = [self.fileHelper fileURLForBuggyWKWebView8:[NSURL fileURLWithPath:path]];
NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
[self.webView loadRequest:request];
}
}

2.Swift

//将文件copy到tmp目录
func fileURLForBuggyWKWebView8(fileURL: NSURL) throws -> NSURL {
// Some safety checks
var error:NSError? = nil;
if (!fileURL.fileURL || !fileURL.checkResourceIsReachableAndReturnError(&error)) {
throw error ?? NSError(
domain: "BuggyWKWebViewDomain",
code: 1001,
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("URL must be a file URL.", comment:"")])
} // Create "/temp/www" directory
let fm = NSFileManager.defaultManager()
let tmpDirURL = NSURL.fileURLWithPath(NSTemporaryDirectory()).URLByAppendingPathComponent("www")
try! fm.createDirectoryAtURL(tmpDirURL, withIntermediateDirectories: true, attributes: nil) // Now copy given file to the temp directory
let dstURL = tmpDirURL.URLByAppendingPathComponent(fileURL.lastPathComponent!)
let _ = try? fileMgr.removeItemAtURL(dstURL)
try! fm.copyItemAtURL(fileURL, toURL: dstURL) // Files in "/temp/www" load flawlesly :)
return dstURL
} //方法调用 var filePath = NSBundle.mainBundle().pathForResource("file", ofType: "pdf") if #available(iOS 9.0, *) {
// iOS9. One year later things are OK.
webView.loadFileURL(fileURL, allowingReadAccessToURL: fileURL)
} else {
// iOS8. Things can be workaround-ed
// Brave people can do just this
// fileURL = try! pathForBuggyWKWebView8(fileURL)
// webView.loadRequest(NSURLRequest(URL: fileURL))
do {
fileURL = try fileURLForBuggyWKWebView8(fileURL)
webView.loadRequest(NSURLRequest(URL: fileURL))
} catch let error as NSError {
print("Error: " + error.debugDescription)
}
}

2. WKWebView - WKNavigationDelegate使用

特别提醒一点,在使用以下delegate的方法时

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler

需执行decisionHandler的block。

例如:

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    NSURLRequest *request = navigationAction.request;
WMPageActionType actionType = ActionTypeNone;
WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;
if([request.URL.absoluteString hasPrefix:OC_CLOSE_REQUEST]){
actionType = ActionTypeClose;
actionPolicy = WKNavigationActionPolicyCancel;
}
if(self.actionDelegate && [self.actionDelegate respondsToSelector:@selector(webView:action:type:)]) {
[self.actionDelegate webView:webView action:navigationAction type:actionType];
}
//这句是必须加上的,不然会异常
decisionHandler(actionPolicy);
}

3.WKWebView-JS执行方法

WKWebView JS执行方法与UIWebView不一样了。

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler;

completionHandler 拥有两个参数,一个是返回错误,一个可以返回执行脚本后的返回值

WKWebView使用遇到的坑--加载本地html及JS交互的更多相关文章

  1. #iOS问题记录#动态Html加载本地CSS和JS文件

    所谓动态Html,指代码中组合生成的html字符串: 若需要加载本地CSS,图片,JS文件,则, 1,需要文件的全路径: 2,需要"file:///"标志: 例如: //获取文件全 ...

  2. WebView加载本地html、js文件常见问题及解决办法

    声明:基于android studio平台,php语言搭建服务器 目录: 一.JavaScript脚本语言没有反应 二.alert无法弹出 三.html页面之间不能跳转 四.屏幕缩放没有达到预期效果 ...

  3. 填补Resources和WWW加载本地资源的坑

    总的来说Resources和WWW加载本地资源坑比较多,大多与路径有关. 下面代码构成了一个路径的预读模块: 此模块主要解决的坑是:Resources或WWW加载本地的文件夹中的多个文件时,无法获取文 ...

  4. WKWebView 加载本地HTML显示不出网页问题,这点你注意了吗?-------完美显示

    1.首先,WKWebView的引入和创建,我这里就不做阐述,我要说的,就是解决别人不能给您解决的问题 2.WKWebView 加载本地HTML,也就是两三句代码  是吧?作为读者的您肯定也知道,也实现 ...

  5. swift 加载 本地html 和 网络路径

    先上代码: xcode 9.4  ios 11.4 import UIKit import WebKit class RootViewController: UIViewController, WKN ...

  6. 重新想象 Windows 8.1 Store Apps (81) - 控件增强: WebView 之加载本地 html, 智能替换 html 中的 url 引用, 通过 Share Contract 分享 WebView 中的内容, 为 WebView 截图

    [源码下载] 重新想象 Windows 8.1 Store Apps (81) - 控件增强: WebView 之加载本地 html, 智能替换 html 中的 url 引用, 通过 Share Co ...

  7. iOS --- UIWebView的加载本地数据的三种方式

    UIWebView是IOS内置的浏览器,可以浏览网页,打开文档  html/htm  pdf   docx  txt等格式的文件.  safari浏览器就是通过UIWebView做的. 服务器将MIM ...

  8. UIWebView加载本地html文件

    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(, , KScreenWidth, KScreenHeight-)]; ...

  9. viewpage listview gridview加载本地大图多图OOM处理办法

    很少上博客园写东西了. 最近在写公司项目,由于需要加载本地相册通过viewpager方式来加载, 最后发现直接进入界面就OOM了. 经过几天的整理最终搞定. 现在将加载本地和加载网络图片的缓存工具类贴 ...

随机推荐

  1. JS简单数据类型

    JS数据类型 在计算机中,不同的数据所需要占用的空间是不同的,为了便于把数据分析称所需内存大小不同的数据,充分利用存储空间,于是定义了不同的数据类型 简单数据类型 简单数据类型 说明 默认值 Numb ...

  2. Cesium专栏-空间分析之地形等高线(附源码下载)

    Cesium Cesium 是一款面向三维地球和地图的,世界级的JavaScript开源产品.它提供了基于JavaScript语言的开发包,方便用户快速搭建一款零插件的虚拟地球Web应用,并在性能,精 ...

  3. 高级语言——java

    高级语言——java 起源与发展 1991 年,James Gosling 博士发布产品 Oak,这是 Java 语言的前身. 1995 年,Oak 语言改名为 Java. 1996 年,JDK(Ja ...

  4. Mysql—数据恢复

    根据.frm和.ibd文件恢复表结构和数据

  5. 反卷积(Transposed Convolution)

    反卷积的具体计算步骤 令图像为 卷积核为 case 1 如果要使输出的尺寸是 5x5,步数 stride=2 ,tensorflow 中的命令为: transpose_conv = tf.nn.con ...

  6. linux 头文件路径

    linux 头文件路径 /usr/include

  7. AcWing 44. 分行从上往下打印二叉树

    地址 https://www.acwing.com/problem/content/description/42/ 题目描述从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行. ...

  8. js SetTimeout传参问题

    今天写代码遇到这样一个问题,先上代码 <!--JS方法--> function textout(obj){ if(opac==60){opac=0;return;}; opac+=10; ...

  9. 深入理解typescript的Functions

    Functions Introduction # Functions are the fundamental building block of any application in JavaScri ...

  10. 开发SSO单点登录需要注意的问题

      一.单点登录系统开发需要注意的问题     1.单点登录系统需要支持jsonp请求?    单点登录系统主要是向其他系统提供用户身份验证服务,因此需要提供对外接口,而外部系统通过接口访问时,必然涉 ...