需求:hybrid混合开发,大概就是把.html
和.css
等资源文件存在本地,通过jsBridge.js
来进行交互,提高在app
中加载h5
页面的加载速度和用户体验等问题,减少app
端需要发包才能解决的一些业务问题。
最近将hybrid
框架中的UIWebView
换成WKWebView
遇到的问题,主要是加载jsBridge.js
文件遇到的问题。
-
UIWebView
中的加载jsBridge.js
,代码如下:
- (void)webViewDidStartLoad:(UIWebView *)webView
{
if (webView != self) { return; }
[webView stringByEvaluatingJavaScriptFromString:[self jsString]];
if ([self.webViewDelegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
[self.webViewDelegate webViewDidStartLoad:webView];
}
}
- (NSString *)jsString {
NSString *result = [NSString stringWithContentsOfFile:JSBridgePath encoding:NSUTF8StringEncoding error:nil];
if (result == nil) {
result = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"jsBridge" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil];
}
return result;
}
像正常加载url
的方法一样就可以了
- (void)reloadWebViewRequest
{
[self.webView loadRequest:[NSURLRequest requestWithURL:self.url]];
}
2.WKWebView
中的加载jsBridge.js
,一开始也是直接像UIWebView
一样在代理方法执行jsBridge.js
,虽然js代码执行成功了,但是加载不了存在本地的.html
和.css
等文件,页面就加载不出来,代码如下:
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
if (webView != self) { return; }
[webView evaluateJavaScript:[self jsString] completionHandler:^(id _Nullable, NSError * _Nullable error) {
}];
if ([self.webViewDelegate respondsToSelector:@selector(webView:didFinishNavigation:)]) {
[self.webViewDelegate webView:webView didFinishNavigation:navigation];
}
}
后来在网上找了好多资料,具体实现如下:
// 初始化webview
- (void)viewDidLoad {
[super viewDidLoad];
[self installStartTime];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
self.webview = [[JSBWebView alloc] initWithFrame:self.view.bounds configuration:config];
self.webview.navigationDelegate = self;
self.webview.UIDelegate = self;
}
- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
{
WKUserScript *script = [[WKUserScript alloc] initWithSource:[self jsString] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
[configuration.userContentController addUserScript:script];
[configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
self = [super initWithFrame:frame configuration:configuration];
if (self) {
[self setup];
}
return self;
}
说明,一定要设置[configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
加载文件一定要用loadFileURL:allowingReadAccessToURL:
这个才会生效
- (void)reloadWebViewRequest
{
NSURL *accessURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] objectAtIndex:0];
[self.webview loadFileURL:self.url allowingReadAccessToURL:accessURL];
}
参考资料:
https://stackoverflow.com/questions/40472796/wkwebview-loadfileurl-works-only-once
网友评论