一、Native开发中为什么需要H5容器
Native开发原生应用是手机操作系统厂商(目前主要是苹果的iOS和google的Android)对外界提供的标准化的开发模式,他们对于native开发提供了一套标准化实现和优化方案。但是他们存在一些硬伤,比如App的发版周期偏长、有时无法跟上产品的更新节奏;灵活性差,如果有较大的方案变更,需要发版才能解决;如果存在bug,在当前版本修复的难度比较大(iOS的JSPatch方案和Android的Dex修复方案);需要根据不同的平台写不同的代码,iOS主要为object_c和swift,android为Java。
而作为H5为主要开发模式的Web App的灵活性就比较强,他利用操作系统中的h5容器作为一个承载,对外提供一个url链接,而该url链接对应的内容可以实时在服务端进行修改,灵活行很强,避免了Native发版周期带来的时间成本。但是h5虽然灵活,但是他也有自己的硬伤。每次都需要下载完整的UI数据(html,css,js),弱网用户体验较差,流量消耗较大;无法调用系统文件系统,硬件资源等等;
Native App和Web App都有他们的优势和劣势。我们也不能一棍子拍死说谁好谁劣。通常的经验是:对于一些比较稳当的业务,对用户体验要求较高的,我们可以选择Native开发。而对于一些业务变更比较快、处在不断试水的过程,而且不涉及调用文件系统和硬件调用的业务我们可以选择h5开发。所以说,在一款app中我们需要同时支持Native代码和h5代码。这也是我们标题所说的Native开发中需要H5容器的必要性。
iOS存在的h5容器主要包括UIWebView和WKWebView,下面我们就分别来说说他们的用法和优劣。
二、UIWebView的基本用法
2.1、加载网页
1
2
3
4
5
|
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
webView.delegate = self;
[self.view addSubview:webView];
//网络地址
NSURL *url = [[NSURL alloc] initWithString:@
"http://www.taobao.com"
]; NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
|
2.2、UIWebViewDelegate几个常用的代理方法
1
|
- (
BOOL
)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
//进行加载前的预判断,如果返回YES,则会进入后续流程(StartLoad,FinishLoad)。如果返回NO,这不会进入后续流程。- (void)webViewDidStartLoad:(UIWebView *)webView;//开始加载网页- (void)webViewDidFinishLoad:(UIWebView *)webView;//加载完成- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error;//加载失败
|
2.3、Native调用JS中的方法
比如我们在加载的HTML文件中有如下js代码:
1
2
3
4
5
6
|
<script type=
"text javascript"
=
""
>function hello(){
alert(
"你好!"
);
}function helloWithName(name){
alert(name +
",你好!"
);
}
</script type="text>
|
我们可以调用- (nullable NSString )stringByEvaluatingJavaScriptFromString:(NSString )script;函数进行js调用。
1
|
[webView stringByEvaluatingJavaScriptFromString:@
"hello()"
];[webView stringByEvaluatingJavaScriptFromString:@
"helloWithName('jack')"
];
|
js代码不一定要在js文件中预留,也可以在代码中通过字符串的形式进行调用,比如下面:
1
2
3
4
|
//自定义js函数
NSString *jsString = @
"function sayHello(){ \ alert('jack11') \ } \ sayHello()"
; [_webView stringByEvaluatingJavaScriptFromString:jsString];
NSString *jsString = @
" var p = document.createElement('p'); \ p.innerText = 'New Line'; \ document.body.appendChild(p); \ "
; [_webView stringByEvaluatingJavaScriptFromString:jsString];
|
2.4、JS中调用Naitve的方法
具体让js通知native进行方法调用,我们可以让js产生一个特殊的请求。可以让Native代码可以拦截到,而且不然用户察觉。业界一般的实现方案是在网页中加载一个隐藏的iframe来实现该功能。通过将iframe的src指定为一个特殊的URL,实现在- (BOOL)webView:(UIWebView )webView shouldStartLoadWithRequest:(NSURLRequest )request navigationType:(UIWebViewNavigationType)navigationType;方案中进行拦截处理。对应的js调用代码如下:
1
2
3
4
5
6
7
8
9
10
|
function loadURL(url) { var iFrame;
iFrame = document.createElement(
"iframe"
);
iFrame.setAttribute(
"src"
, url);
iFrame.setAttribute(
"style"
,
"display:none;"
);
iFrame.setAttribute(
"height"
,
"0px"
);
iFrame.setAttribute(
"width"
,
"0px"
);
iFrame.setAttribute(
"frameborder"
,
"0"
); document.body.appendChild(iFrame);
// 发起请求后这个iFrame就没用了,所以把它从dom上移除掉
iFrame.parentNode.removeChild(iFrame);
iFrame = null;
}
|
比如我们在js代码中,调用一下两个js方法:
1
2
3
4
5
|
function iOS_alert() {
//调用自定义对话框
} function call() {
// js中进行拨打电话处理
}
|
当你触发以上方法的时候,就会进入webview的代理方法中进行拦截。
1
2
3
4
5
6
7
8
9
|
- (
BOOL
)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ NSURL * url = [request URL];
if
([[url scheme] isEqualToString:@
"alert"
]) {
//拦截请求,弹出自定义对话框
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@
"test"
message:[url host] delegate:nil cancelButtonTitle:@
"OK"
otherButtonTitles:nil];
[alertView show];
return
NO;
}
else
if
([[url scheme] isEqualToString:@
"tel"
]){
//拦截拨打电话请求
BOOL
result = [[UIApplication sharedApplication] openURL:url];
if
(!result) { NSLog(@
"您的设备不支持打电话"
);
}
else
{ NSLog(@
"电话打了"
);
}
return
NO;
}
return
YES;
}
|
这样我们就可以让js进行native的调用。
三、WKWebView的基本用法
3.1、加载网页
1
2
3
|
WKWebView *webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds]; NSURL *url = [NSURL URLWithString:@
"http://www.taobao.com"
]; NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
[self.view addSubview:webView];
|
3.2、几个常用的代理方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
/**
* 根据webView、navigationAction相关信息决定这次跳转是否可以继续进行,这些信息包含HTTP发送请求,如头部包含User-Agent,Accept,refer
* 在发送请求之前,决定是否跳转的代理
* @param webView
* @param navigationAction
* @param decisionHandler
*/
- (
void
)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(
void
(^)(WKNavigationActionPolicy))decisionHandler{
decisionHandler(WKNavigationActionPolicyAllow);
}
/**
* 这个代理方法表示当客户端收到服务器的响应头,根据response相关信息,可以决定这次跳转是否可以继续进行。
* 在收到响应后,决定是否跳转的代理
* @param webView
* @param navigationResponse
* @param decisionHandler
*/
- (
void
)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(
void
(^)(WKNavigationResponsePolicy))decisionHandler{
decisionHandler(WKNavigationResponsePolicyAllow);
}
/**
* 准备加载页面。等同于UIWebViewDelegate: - webView:shouldStartLoadWithRequest:navigationType
*
* @param webView
* @param navigation
*/
- (
void
)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
}
/**
* 这个代理是服务器redirect时调用
* 接收到服务器跳转请求的代理
* @param webView
* @param navigation
*/
- (
void
)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
}
- (
void
)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
}
/**
* 内容开始加载. 等同于UIWebViewDelegate: - webViewDidStartLoad:
*
* @param webView
* @param navigation
*/
- (
void
)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation{
}
/**
* 页面加载完成。 等同于UIWebViewDelegate: - webViewDidFinishLoad:
*
* @param webView
* @param navigation
*/
- (
void
)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
}
/**
* 页面加载失败。 等同于UIWebViewDelegate: - webView:didFailLoadWithError:
*
* @param webView
* @param navigation
* @param error
*/
- (
void
)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
}
- (
void
)webViewWebContentProcessDidTerminate:(WKWebView *)webView NS_AVAILABLE(10_11, 9_0){
}
/*
我们看看WKUIDelegate的几个代理方法,虽然不是必须实现的,但是如果我们的页面中有调用了js的alert、confirm、prompt方法,我们应该实现下面这几个代理方法,然后在原来这里调用native的弹出窗,因为使用WKWebView后,HTML中的alert、confirm、prompt方法调用是不会再弹出窗口了,只是转化成ios的native回调代理方法
*/
#pragma mark - WKUIDelegate- (
void
)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(
void
(^)(
void
))completionHandler{ UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@
"h5Container"
message:message preferredStyle:UIAlertControllerStyleAlert];
// [alertView addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {// textField.textColor = [UIColor redColor];// }];
[alertView addAction:[UIAlertAction actionWithTitle:@
"我很确定"
style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alertView animated:YES completion:nil];
}
|
显然WKWebView的代理方法提供了比UIWebView颗粒度更细的方法。让开发者可以进行更加细致的配置和处理。
3.3 、Native调用JS中的方法
WKWebView提供的调用js代码的函数是:
1
|
- (
void
)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(
void
(^ __nullable)(__nullable id, NSError * __nullable error))completionHandler;
|
比如我们在加载的HTML文件中有如下js代码:
1
2
3
4
5
6
|
<script type=
"text javascript"
=
""
>function hello(){
alert(
"你好!"
);
}function helloWithName(name){
alert(name +
",你好!"
);
}
</script type="text>
|
我们可以调用如下代码进行js的调用:
1
2
3
4
5
6
7
|
[_wkView evaluateJavaScript:@
"hello()"
completionHandler:^(id item, NSError * error) {
}];
[_wkView evaluateJavaScript:@
"helloWithName('jack')"
completionHandler:^(id item, NSError *error) {
}];
|
同UIWebView一样,我们也可以通过字符串的形式进行js调用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
NSString *jsString = @"function sayHello(){ \
alert(
'jack11'
) \
} \
sayHello()";
[_wkView evaluateJavaScript:jsString completionHandler:^(id item, NSError *error) {
}];
jsString = @" var p = document.createElement(
'p'
); \
p.innerText =
'New Line'
; \
document.body.appendChild(p); \
";
[_wkView evaluateJavaScript:jsString completionHandler:^(id item, NSError *error) {
}];
|
3.4、JS中调用Naitve的方法
除了和UIWebView加载一个隐藏的ifame之外,WKWebView自身还提供了一套js调用native的规范。
我们可以在初始化WKWebView的时候,给他设置一个config参数。
1
2
3
4
5
6
7
8
9
10
11
|
//高端配置
//创建配置
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
//创建UserContentController(提供javaScript向webView发送消息的方法)
WKUserContentController *userContent = [[WKUserContentController alloc] init];
//添加消息处理,注意:self指代的是需要遵守WKScriptMessageHandler协议,结束时需要移除
[userContent addScriptMessageHandler:self name:@
"NativeMethod"
];
//将UserContentController设置到配置文件中
config.userContentController = userContent;
//高端的自定义配置创建WKWebView
_wkView = [[YXWKView alloc] initWithFrame:self.view.bounds configuration:config]; NSURL *url = [NSURL URLWithString:@
"http://localhost:8080/myDiary/index.html"
]; NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_wkView loadRequest:request];
_wkView.UIDelegate = self;
_wkView.navigationDelegate = self;
[self.view addSubview:_wkView];
|
我们在js可以通过NativeMethod这个Handler让js代码调用native。
比如在js代码中,我新增了一个方法
1
2
3
|
<script type=
"text javascript"
=
""
> function invokeNativeMethod(){ window.webkit.messageHandlers.NativeMethod.postMessage(
"我要调用native的方法"
);
}
</script type="text>
|
触发以上方法的时候,会在native以下方法中进行拦截处理。
1
2
3
4
|
#pragma mark - WKScriptMessageHandler- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ //这里就是使用高端配置,js调用native的处理地方。我们可以根据name和body,进行桥协议的处理。
NSString *messageName = message.name;
if
([@
"NativeMethod"
isEqualToString:messageName]) { id messageBody = message.body; NSLog(@
"%@"
,messageBody);
}
}
|
四、UIWebView和WKWebView的比较和选择
WKWebView是苹果在WWDC2014发布会中发布IOS8的时候公布WebKit时候使用的新型的H5容器。它与UIWebView相比较,拥有更快的加载速度和性能,更低的内存占用。将UIWebViewDelegate和UIWebView重构成了14个类,3个协议,可以让开发者进行更加细致的配置。
但是他有一个最致命的缺陷,就是WKWebView的请求不能被NSURLProtocol截获。而我们团队开发的app中对于H5容器最佳的优化点主要就在于使用NSURLProtocol技术对于H5进行离线包的处理和H5的图片和Native的图片公用一套缓存的技术。因为该问题的存在,目前我们团队还没有使用WKWebView代替UIWebVIew。
五、联系方式
一、前言
NSURLProtocol是iOS中URL Loading System的一部分。如果开发者自定义的一个NSURLProtocol并且注册到app中,那么在这个自定义的NSURLProtocol中我们可以拦截UIWebView,基于系统的NSURLConnection或者NSURLSession进行封装的网络请求,然后做到自定义的response返回。非常强大。
二、NSURLProtocol的使用流程
2.1、在AppDelegate中注册自定义的NSURLProtocol。
比如我这边自定义的NSURLProtocol叫做YXNSURLProtocol。
1
2
|
@interface YXNSURLProtocol : NSURLProtocol
@end
|
在系统加载的时候,把自定义的YXNSURLProtocol注册到URL加载系统中,这样 所有的URL请求都有机会进入我们自定义的YXNSURLProtocol进行拦截处理。
1
2
3
|
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[NSURLProtocol registerClass:[YXNSURLProtocol class]];
}
|
加载完成后,当产生URL请求的同时,会依次进入NSURLProtocol的以下相关方法进行处理,下面我们依次来讲一下每一个方法的作用。
2.2、NSURLProtocol中的几个方法
2.2.1、是否进入自定义的NSURLProtocol加载器
1
2
3
4
5
6
7
8
|
+ (BOOL)canInitWithRequest:(NSURLRequest *)request{
BOOL intercept = YES;
NSLog(@"YXNSURLProtocol==%@",request.URL.absoluteString);
if (intercept) {
}
return intercept;
}
|
如果返回YES则进入该自定义加载器进行处理,如果返回NO则不进入该自定义选择器,使用系统默认行为进行处理。
如果这一步骤返回YES。则会进入2.3的方法中。
2.2.2、重新设置NSURLRequest的信息
1
2
3
|
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
return request;
}
|
在这个方法中,我们可以重新设置或者修改request的信息。比如请求重定向或者添加头部信息等等。如果没有特殊需求,直接返回request就可以了。但是因为这个方法在会在一次请求中被调用多次(暂时我也不知道什么原因为什么需要回调多洗),所以request重定向和添加头部信息也可以在开始加载中startLoading方法中重新设置。
2.2.3、这个方法主要是用来判断两个request是否相同,如果相同的话可以使用缓存数据,通常调用父类的实现即可
1
2
3
|
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b{
return [super requestIsCacheEquivalent:a toRequest:b];
}
|
这个方法基本不常用。
2.2.4、被拦截的请求开始执行的地方
1
2
|
- (void)startLoading{
}
|
这个函数使我们重点使用的函数。
2.2.5、结束加载URL请求
1
2
|
- (void)stopLoading{
}
|
2.3、NSURLProtocolClient中的几个方法
上面的NSURLProtocol定义了一系列加载的流程。而在每一个流程中,我们作为使用者该如何使用URL加载系统,则是NSURLProtocolClient中几个方法该做的事情。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
@protocol NSURLProtocolClient
//请求重定向
- (void)URLProtocol:(NSURLProtocol *)protocol wasRedirectedToRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse;
// 响应缓存是否合法
- (void)URLProtocol:(NSURLProtocol *)protocol cachedResponseIsValid:(NSCachedURLResponse *)cachedResponse;
//刚接收到Response信息
- (void)URLProtocol:(NSURLProtocol *)protocol didReceiveResponse:(NSURLResponse *)response cacheStoragePolicy:(NSURLCacheStoragePolicy)policy;
//数据加载成功
- (void)URLProtocol:(NSURLProtocol *)protocol didLoadData:(NSData *)data;
//数据完成加载
- (void)URLProtocolDidFinishLoading:(NSURLProtocol *)protocol;
//数据加载失败
- (void)URLProtocol:(NSURLProtocol *)protocol didFailWithError:(NSError *)error;
//为指定的请求启动验证
- (void)URLProtocol:(NSURLProtocol *)protocol didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
//为指定的请求取消验证
- (void)URLProtocol:(NSURLProtocol *)protocol didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
@end
|
三、实现一个地址重定向的Demo
这个Demo实现的功能是在UIWebView中所有跳转到sina首页的请求,都重定位到sohu首页。
3.1、第一步,新建一个UIWebView,加载sina首页
1
2
3
4
5
6
|
_webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
_webView.delegate = self;
[self.view addSubview:_webView];
NSURL *url = [[NSURL alloc] initWithString:@"https://sina.cn"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_webView loadRequest:request];
|
3.2、自定义一个NSURLProtocol
1
2
3
|
@interface YXNSURLProtocolTwo : NSURLProtocol
@end
|
3.3、在AppDelegate中,进行注册
1
2
3
4
|
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[NSURLProtocol registerClass:[YXNSURLProtocolTwo class]];
return YES;
}
|
3.4、在canInitWithRequest方法中拦截https://sina.cn/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
+ (BOOL)canInitWithRequest:(NSURLRequest *)request{
NSLog(@"canInitWithRequest url-->%@",request.URL.absoluteString);
//看看是否已经处理过了,防止无限循环
if ([NSURLProtocol propertyForKey:URLProtocolHandledKey inRequest:request]) {
return NO;
}
NSString *urlString = request.URL.absoluteString;
if([urlString isEqualToString:@"https://sina.cn/"]){
return YES;
}
return NO;
}
|
3.5、在startLoading中进行方法重定向
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
- (void)startLoading{
NSMutableURLRequest * request = [self.request mutableCopy];
// 标记当前传入的Request已经被拦截处理过,
//防止在最开始又继续拦截处理
[NSURLProtocol setProperty:@(YES) forKey:URLProtocolHandledKey inRequest:request];
self.connection = [NSURLConnection connectionWithRequest:[self changeSinaToSohu:request] delegate:self];
}
//把所用url中包括sina的url重定向到sohu
- (NSMutableURLRequest *)changeSinaToSohu:(NSMutableURLRequest *)request{
NSString *urlString = request.URL.absoluteString;
if ([urlString isEqualToString:@"https://sina.cn/"]) {
urlString = @"http://m.sohu.com/";
request.URL = [NSURL URLWithString:urlString];
}
return request;
}
|
你也可以选择在+ (NSURLRequest )canonicalRequestForRequest:(NSURLRequest )request
替换request。效果都是一样的。
3.6、因为新建了一个NSURLConnection *connection,所以要实现他的代理方法,如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.client URLProtocol:self didLoadData:data];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
[self.client URLProtocolDidFinishLoading:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[self.client URLProtocol:self didFailWithError:error];
}
|
通过以上几步,我们就可以实现最简单的url重定向,WebView加载新浪首页,却跳转到了搜狐首页。
四、小结
通过自定义的NSURLProtocol,我们拿到用户请求的request之后,我们可以做很多事情。比如:
1、自定义请求和响应
2、网络的缓存处理(H5离线包 和 网络图片缓存)
3、重定向网络请求
4、为测试提供数据Mocking功能,在没有网络的情况下使用本地数据返回。
5、过滤掉一些非法请求
6、快速进行测试环境的切换
8、可以拦截UIWebView,基于系统的NSURLConnection或者NSURLSession进行封装的网络请求。目前WKWebView无法被NSURLProtocol拦截。
9、当有多个自定义NSURLProtocol注册到系统中的话,会按照他们注册的反向顺序依次调用URL加载流程。当其中有一个NSURLProtocol拦截到请求的话,后续的NSURLProtocol就无法拦截到该请求。