最近在做一些与H5 交互的活动,刚开始接触,也不是很了解,然后跟H5 同事对接上有点吃不消,然后在网上找了一些文章学习了一下。现在就总结一下自己跟H5 调试的一些经验。
与H5 交互的那点事
拦截协议
一、UIWebView 的简单使用
1. 加载 html 的方式: 加载本地html 和 网络html
加载本地 html:
- (void)setupUIWebView
{
UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
//加载网络 html
// [web loadRequest:[self urlRequest]];
web.delegate = self;
[self.view addSubview:web];
_webView = web;
//加载本地 html
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"java" ofType:@"html"];
NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSURL *url = [[NSURL alloc] initWithString:filePath];
[_webView loadHTMLString:htmlString baseURL:url];
}
加载网络 html:(如果网页约定要校验的话,按照双方的约定,制定请求头)例如:
- (NSURLRequest *)urlRequest
{
NSString *urlStr = @"http://xxxx.xxxx.com/share_test/index";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableDictionary *dict=[NSMutableDictionary dictionary];
[dict setObject:@"123" forKey:@"username"];
[dict setObject:@"true" forKey:@"isapp"];
[dict setObject:@"ios" forKey:@"os"];
[dict setObject:[NSString stringWithFormat:@"%@",@"v1.4.2"] forKey:@"version"];
NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval a=[dat timeIntervalSince1970];
NSString *timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
NSInteger rand10_num = arc4random()%9000000000 + 1000000000;
NSString *signFirstStr = [NSString stringWithFormat:@"%@%@%@",timeString,@"123",@"DM23985xxxx"];
NSString * md5First = [signFirstStr md5];
NSString * singSecStr = [NSString stringWithFormat:@"%@%zd",md5First,rand10_num];
NSString * md5SignStr = [singSecStr md5];
[dict setObject:timeString forKey:@"timestamp"];
[dict setObject:[NSString stringWithFormat:@"%zd",rand10_num] forKey:@"key"];
[dict setObject:md5SignStr forKey:@"sign"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setAllHTTPHeaderFields:dict];
return request;
}
⚠️前方高能:接下来就是交互的事情了
1.1 首先是客户端调用 H5 方法
方法一:
通过: stringByEvaluatingJavaScriptFromString:它可以返回 H5 方法的返回值,一般是 json ,但是绑定了模型之后就不会有返回值了,返回空字符
例如:[_webView stringByEvaluatingJavaScriptFromString:@"jsShare();"];
方法二:block 交互的方式
绑定block,通过执行 H5 方法,执行block 事件
⚠️注意:这种方式好像不能取得H5 方法的返回值,不知道怎么获取,还请高人指教
如下:
// block 方式
JSContext *context = [[JSContext alloc] init];
// 定义一个block ,⚠️注意:context[@"jsShare"] 和 [context evaluateScript:@"jsShare();"]; 这里面的@"" H5 的方法,并且要一致
context[@"jsShare"] = ^() {
[self jsCallClientAlertWithTitle:@"H5" message:@"调用js执行jsShare方法"];
};
// 调用js执行jsShare方法
JSValue *value = [context evaluateScript:@"jsShare();"];
//但是这里取不到H5 的返回值
1.2 其次H5 调用客户端方法,我们需要通过代理方法来实现
1.2.1 协议拦截
/** 准备加载的使用调用 在这里拦截协议最好
* return YES 才开始加载网页
* return NO 不会加载网页
*/
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(@"UIWebView: 协议拦截");
NSString *urlStr = request.URL.absoluteString;
NSLog(@"url = %@",urlStr);
if ([urlStr containsString:@"app://showAlert"]) {
[self clientDoAlertbyItself];
return NO;
} else if ([urlStr containsString:@"app://presentVC"]) {
[self presentViewController:[TestViewController new] animated:YES completion:nil];
return NO;
}
return YES;
}
1.2.2 注入模型使用代理方式--调用客户端方法
注入位置:documentView.webView.mainFrame.javaScriptContext
注意:⚠️_content[@"xxx"] 与 H5 里面的一样,具体实现请参考html 里面的代码
/** 网页完成加载的时候调用 */
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@"UIWebView: %s", __func__);
// 注入模型使用代理 方式
//注入js函数
_content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
ShareJsObject *test = [ShareJsObject new];
test.shareDelegate = self;
_content[@"client"] = test;
/*
* oc调用js 异常时
* 例如 oc调用js 函数不存在
*/
_content.exceptionHandler = ^(JSContext *context, JSValue *exception) {
context.exception = exception;
NSLog(@"toString === %@", exception.toString);
};
}
最后记得返回上一个页面时清楚缓存哦!
/** 清除缓存 */
- (void)cleanAllCacheAndCookie{
NSLog(@"%s", __func__);
//清除cookies
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]){
[storage deleteCookie:cookie];
}
//清除UIWebView的缓存
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSURLCache * cache = [NSURLCache sharedURLCache];
[cache removeAllCachedResponses];
[cache setDiskCapacity:0];
[cache setMemoryCapacity:0];
}
---------------------------------------------------------------------------------------------------------------------------分割线 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
二、WKWebView 的简单使用
加载方式和 UIWebView 一样的,但是加载的网页有可能不适应手机屏幕,显得网页字太小,就要适应我们的手机屏幕
- (void)setupWKWebView
{
//这里我们通过 WKUserContentController 绑定 H5 的方法,通过该对象代理进行调用客户端方法
WKUserContentController *contentCtrl = [[WKUserContentController alloc] init];
[contentCtrl addScriptMessageHandler:[[WeakScriptDelegate alloc] initWithDelegate:self] name:@"jsWkShare"];
[contentCtrl addScriptMessageHandler:[[WeakScriptDelegate alloc] initWithDelegate:self] name:@"WKOpenCamera"];
WKWebViewConfiguration *conf = [[WKWebViewConfiguration alloc] init];
conf.userContentController = contentCtrl;
//适应手机屏幕
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[contentCtrl addUserScript:wkUScript];
WKWebView *web = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) configuration:conf];
NSString *urlPath = [[NSBundle mainBundle] pathForResource:@"java.html" ofType:nil];
NSString *htmlStr = [NSString stringWithContentsOfFile:urlPath encoding:NSUTF8StringEncoding error:nil];
if (!htmlStr) {
[web loadRequest:[self urlRequest]];
} else{
NSURL *url = [NSURL fileURLWithPath:urlPath];//[[NSURL alloc] initWithString:urlPath];
[web loadHTMLString:htmlStr baseURL:url];
}
[self.view addSubview:web];
web.navigationDelegate = self;
web.UIDelegate = self;
_wkWebView = web;
}
⚠️前方高能:接下来就是交互的事情了
2.1 首先是客户端调用 H5 方法
[_wkWebView evaluateJavaScript:@"WKOpenCamera();" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSLog(@"==%@",response);
}];
2.2 其次 H5 方法调用客户端方法
2.2.1 协议拦截
/** 是否允许加载网页 在发送请求之前,决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
NSLog(@"WKWebView: 协议拦截");
NSLog(@"%s", __func__);
NSString *urlStr = navigationAction.request.URL.absoluteString;
NSLog(@"url = %@",urlStr);
if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
if ([urlStr containsString:@"app://showAlert"]) {
[self clientDoAlertbyItself];
decisionHandler(WKNavigationActionPolicyCancel);
} else if ([urlStr containsString:@"app://presentVC"]) {
[self presentViewController:[TestViewController new] animated:YES completion:nil];
decisionHandler(WKNavigationActionPolicyCancel);
}
} else {
decisionHandler(WKNavigationActionPolicyAllow);
}
}
2.2.2 通过代理
这里我们通过 WKUserContentController 绑定 H5 的方法,通过该对象代理进行调用客户端方法
⚠️注意:这里为什么会有 WeakScriptDelegate 这个类呢,其实这里直接绑定 self 也是可以的,但是呢!这里会导致加载 WKWebView 的控制器不释放,weakSelf 也是不能的(不知道为什么?),所以用 WeakScriptDelegate 这个类来背锅。
[contentCtrl addScriptMessageHandler:self name:@"jsWkShare"];
例如:
//这里我们通过 WKUserContentController 绑定 H5 的方法,通过该对象代理进行调用客户端方法
WKUserContentController *contentCtrl = [[WKUserContentController alloc] init];
[contentCtrl addScriptMessageHandler:[[WeakScriptDelegate alloc] initWithDelegate:self] name:@"jsWkShare"];
[contentCtrl addScriptMessageHandler:[[WeakScriptDelegate alloc] initWithDelegate:self] name:@"WKOpenCamera"];
WeakScriptDelegate 的写法,直接写在当前控制器就好
//写在 .h 文件中
@interface WeakScriptDelegate : NSObject
@property (nonatomic, weak) id scriptDelegate;
- (instancetype)initWithDelegate:(id)scriptDelegate;
@end
//写在 .m 文件中
@implementation WeakScriptDelegate
- (instancetype)initWithDelegate:(id)scriptDelegate {
self = [super init];
if (self) {
_scriptDelegate = scriptDelegate;
}
return self;
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
[self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
}
@end
H5 调用之后,就会触发 WKUserContentController 的代理方法,就是以下方法来反馈给客户端,我们在这里做相应的操作,而且能获取得到 H5 方法的返回值。
例如:
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
//通过 message 的 body 和 name 属性取得相应的内容,一般 H5 方法,返回值都在 body 里面
NSLog(@"body == %@",message.body);
NSLog(@"name == %@",message.name);
if (message.body) {
__weak typeof(self) weakSelf = self;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[message.body dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
NSString *title = [dict objectForKey:@"title"];
NSString *desc = [dict objectForKey:@"desc"];
NSString *shareUrl = [dict objectForKey:@"shareUrl"];
if (!title) title = message.name;
if (!desc) desc = message.body;
[weakSelf jsCallClientAlertWithTitle:title message:[NSString stringWithFormat:@"%@\n%@", desc,shareUrl]];
}
}
最后就是清除缓存了和 UIWebView 差不多,但是 iOS 9 之后,得用WKWebView 相应清除得方法,如下:
- (void)cleanCache
{
if (@available(iOS 9.0, *)) {
NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
}];
} else {
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
[storage deleteCookie:cookie];
}
NSURLCache * cache = [NSURLCache sharedURLCache];
[cache removeAllCachedResponses];
[cache setDiskCapacity:0];
[cache setMemoryCapacity:0];
}
}
最后的最后,上一个 Demo 吧! 详细的内容都在代码中,不对的地方,请大神们指出。