注册

iOS---webView相关及原生和web的交互


webView的基本应用,监听加载进度,返回上一页,异常处理web调用原生:处理跳转到指定的原生页面,拦截跳转其他app,添加app白名单,拦截通用链接跳转,js注入,关闭webView原生调用web:获取webView的标题等web原生互相调用:web获取app当前的id、token等用户信息微信web里打开原生app

一、webView的基本应用

现在基本每个app都会或多或少用到web来实现快速迭代。正常都会将其封装在一个控制器里,以使其样式、功能统一
(iOS8引入了WKWebView,使用独立的进程渲染web,解决了之前UIWebView内存泄漏和crash率高等被诟病已久的问题,所以现在基本都是用WKWebView了)


    //如果不考虑和原生的交互
_webView = [[WKWebView alloc] initWithFrame:CGRectZero];
[self.view addSubview:_webView];
[_webView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
_webView.UIDelegate = self;
_webView.navigationDelegate = self;
[_webView loadRequest:[NSURLRequest requestWithURL:URL]];//这里的url是经过校检的

如果要监听webview的加载进度

    //kvo监听
[_webView addObserver:self forKeyPath:@"estimatedProgress" options:0 context:nil];

//创建加载进度条UIProgressView
{
init progressView
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if (object == _webView && [keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]) {
self.progressView.alpha = 1.0f;
BOOL animated = _webView.estimatedProgress > self.progressView.progress;
[self.progressView setProgress:_webView.estimatedProgress animated:animated];

if (_webView.estimatedProgress >= 1.0f) {
[UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
self.progressView.alpha = 0.0f;
} completion:^(BOOL finished) {}];
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
返回上一页

        //kvo监听
[_webView addObserver:self forKeyPath:@"canGoBack" options:0 context:nil];//监听是否有上一页

//configBackButton里判断canGoBack,如果不可以返回就将按钮置灰或者隐藏
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if (object == _webView && [keyPath isEqual: @"canGoBack"]) {
[self configBackButton];
}
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
[self configBackButton];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
[self configBackButton];
}

//按钮事件
if ([weakSelf.webView canGoBack]) {
[weakSelf.webView goBack];
}
当 WKWebView 总体内存占用过大,页面即将白屏的时候,系统会调用下面的回调函数,我们在这里执行[webView reload]解决白屏问题

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {

[webView reload];
}

二、web调用原生

1.这三个代理方法是可以接收到web的调用比如 window.prompt("xxx")

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler;
  1. 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSURL *url = navigationAction.request.URL;
//可以在这里处理一些跳转,比如通过scheme来处理跳转到指定的原生页面(xxx://xxx),拦截跳转其他app,添加app白名单,拦截通用链接跳转等等

//比如
if ([@"mailto" isEqualToString:url.scheme] || [@"tel" isEqualToString:url.scheme]) {//系统scheme
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
decisionHandler(WKNavigationActionPolicyCancel);
} if ([@"xxxx" isEqualToString:url.scheme]) {
// 如果该scheme是你定义好的scheme,可以根据后面的参数去处理跳转到app内的指定页面,或者其他操作
decisionHandler(WKNavigationActionPolicyCancel);
}else if ([scheme白名单 containsObject:url.scheme]) {//白名单
// 打开scheme
[[UIApplication sharedApplication] openURL:url];
decisionHandler(WKNavigationActionPolicyCancel);
} else {
BOOL canOpenUniversalUrl = NO;
for (NSString *str in universalLink白名单) {
if ([url.absoluteString rangeOfString:str].location != NSNotFound) {
canOpenUniversalUrl = YES;
break;
}
}
if (canOpenUniversalUrl) {
// 打开通用链接
decisionHandler(WKNavigationActionPolicyAllow);
} else {
// Default 可以正常访问网页,但禁止打开通用链接
decisionHandler(WKNavigationActionPolicyAllow+2);
}
}
}
web只需
window.location.href = "xxx"//这里的地址就是上方代理方法的url
WKWebView可以使用WKScriptMessageHandler来实现JS调用原生方法
首先初始化的时候,这里拿最常用的web调用关闭webView:xxx_close举例(也可以用上边的href的scheme方式实现,但不太合理)
    _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:[self configWKConfiguration]];

// config,js注入
- (WKWebViewConfiguration *)configWKConfiguration {
WKWebViewConfiguration* webViewConfig = [WKWebViewConfiguration new];
WKUserContentController *userContentController = [WKUserContentController new];
//这里如果用的不多,可以不用单独写一个js文件,直接用字符串就行了
NSString *jsStr = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"js文件地址"] encoding:NSUTF8StringEncoding error:nil];
WKUserScript *userScript = [[WKUserScript alloc] initWithSource:jsStr injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
[userContentController addUserScript:userScript];
[userContentController addScriptMessageHandler:self name:"closeWebView"];

webViewConfig.userContentController = userContentController;
webViewConfig.preferences = [[WKPreferences alloc] init];
webViewConfig.preferences.javaScriptEnabled = YES;
return webViewConfig;
}

//app里的js文件里实现
var xxx = {
close: function() {
window.webkit.messageHandlers.closeWebView.postMessage(null);
},
}

//在这里能收到回调
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
if ([message.name isEqualToString:@"closeWebView"]) {
// 关闭页面
[self.navigationController popViewControllerAnimated:YES];
}
}

web中只需
      try {
window.xxx.close();
} catch (err) {}

三、原生调用web,就是app调用web里的js方法

1.比较常用的一种,获取webView的标题
//也可以用正则去获取标题、图片之类的

    [webView evaluateJavaScript:@"document.title" completionHandler:^(id result, NSError * _Nullable error) {
}];

四. web原生互相调用

比如一个场景,在web里获取app当前登录的账号id

  1. 首先像上边一样,通过js注入的方式web向app发送getUserId请求,app也要同步处理

//web代码

      try {
window.xxx.getUserId();//这里可以直接加返回值,但是app内的js没办法直接去获取原生用户信息这些变量,所以还是要通过原生的代理去实现
} catch (err) {}
  1. 这时候app接收到这个请求,但还要将userId告诉web

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:"getUserId"]){
NSDictionary *dict = xxx;//因为这个过程是异步的,所以这里最好多加一点信息,以便于web确认该结果是上边请求的返回
NSString * jsMethod = [NSString stringWithFormat:@"window.getUserId(%@)",[dict yy_modelToJSONString]];
[webView evaluateJavaScript:@"xxx" completionHandler:^(id result, NSError * _Nullable error) {
}];
}
}

  1. web需要将getUserId方法挂载到window上,算是自定义回调,将上一步生成的用户信息dic当成参数传进来,然后去处理接收到的信息

//web代码

    window["getUserId"] = function(value) {
//在这里解析处理接收到的用户信息
};

五. web如何在微信里打开原生?

普通的scheme跳转被微信给禁了,所以现在基本都是通过universalLink通用链接的方式,设置universalLink的方式网上有好多,另外通用链接可以设置多个,最好设置两个以上(因为这里有个隐藏的坑:web的域名不能和universalLink一样,否则无法跳转)
web代码:


window.location.href = '通用链接://具体落地页'//可以通过参数跳转到具体的页面
作者:Theendisthebegi
链接:https://www.jianshu.com/p/d66d694b762f










0 个评论

要回复文章请先登录注册