当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOs迁至WKWebView跨过的一些坑

iOs迁至WKWebView跨过的一些坑

2020年03月09日  | 移动技术网移动技术  | 我要评论

前言

在ios中有两种网页视图可以加载网页除了系统的那个控制器。一种是uiwebview,另一种是wkwebview,其实wkwebview就是想替代uiwebview的,因为我们都知道uiwebview非常占内存等一些问题,但是现在很多人还在使用uiwebview这是为啥呢?而且官方也宣布在ios12中废弃了uiwebview让我们尽快使用wkwebview。其实也就是这些东西:**页面尺寸问题、js交互、请求拦截、cookie带不上的问题。**所以有时想要迁移还得解决这些问题,所以还是很烦的,所以一一解决喽。

页面尺寸的问题

我们知道有些网页在uiwebview上显示好好地,使用wkwebview就会出现尺寸的问题,这时很纳闷,安卓也不会,你总不说是前端的问题吧?但其实是wkwebview中网页是需要适配一下,所以自己添加js吧,当然和前端关系好就可以叫他加的。下面通过设置配置中的usercontentcontroller来添加js。

wkwebviewconfiguration *configuration = [[wkwebviewconfiguration alloc] init];
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];
wkusercontentcontroller *wkucontroller = [[wkusercontentcontroller alloc] init];
[wkucontroller adduserscript:wkuscript];
configuration.usercontentcontroller = wkucontroller;

js交互

我们都知道在uiwebview中可以使用自家的javascriptcore来进行交互非常的方便。在javascriptcore中有三者比较常用那就是jscontext(上下文)、jsvalue(类型转换)、jsexport(js调oc模型方法)。

在uiwebview中的便利交互方法

//jscontext就为其提供着运行环境 h5上下文
- (void)webviewdidfinishload:(uiwebview *)webview{
 jscontext *jscontext = [self.webview valueforkeypath:@"documentview.webview.mainframe.javascriptcontext"];
 self.jscontext = jscontext;
}
// 执行脚本增加js全局变量
[self.jscontext evaluatescript:@"var arr = [3, '3', 'abc'];"];
// ⚠️添加js方法,需要注意的是添加的方法会覆盖原有的js方法,因为我们是在网页加载成功后获取上下文来操作的。
// 无参数的
self.jscontext[@"alertmessage"] = ^() {
 nslog(@"js端调用alertmessage时就会跑到这里来!");
};
// 带参数的,值必须进行转换
 self.jscontext[@"showdict"] = ^(jsvalue *value) {
 nsarray *args = [jscontext currentarguments];
 jsvalue *dictvalue = args[0];
 nsdictionary *dict = dictvalue.todictionary;
 nslog(@"%@",dict);
 };
// 获取js中的arr数据
jsvalue *arrvalue = self.jscontext[@"arr"];
// 异常捕获
self.jscontext.exceptionhandler = ^(jscontext *context, jsvalue *exception) {
 weakself.jscontext.exception = exception;
 nslog(@"exception == %@",exception);
};
// 给js中的对象重新赋值
omjsobject *omobject = [[omjsobject alloc] init];
self.jscontext[@"omobject"] = omobject;
nslog(@"omobject == %d",[omobject getsum:20 num2:40]);

// 我们都知道object必须要遵守jsexport协议时,js可以直接调用object中的方法,并且需要把函数名取个别名。在js端可以调用gets,oc可以继续使用这个getsum这个方法
@protocol omprotocol <jsexport>
// 协议 - 协议方法 
jsexportas(gets, -(int)getsum:(int)num1 num2:(int)num2);
@end

在wkwebview中如何做呢?

不能像上面那样,系统提供的是通过以下两种方法,所以是比较难受,而且还得前端使用messagehandler来调用,即安卓和ios分开处理。

// 直接调用js
nsstring *jsstr = @"var arr = [3, '3', 'abc']; ";
[self.webview evaluatejavascript:jsstr completionhandler:^(id _nullable result, nserror * _nullable error) {
 nslog(@"%@----%@",result, error);
}];
// 下面是注册名称后,js使用messagehandlers调用了指定名称就会进入到代理中

// oc我们添加了js名称后
- (void)viewdidload{
 //...
 [wkucontroller addscriptmessagehandler:self name:@"showtime"];
 configuration.usercontentcontroller = wkucontroller;
}

// js中messagehandlers调用我们在oc中的名称一致时就会进入后面的到oc的代理
window.webkit.messagehandlers.showtime.postmessage('');

// 代理,判断逻辑
- (void)usercontentcontroller:(wkusercontentcontroller *)usercontentcontroller didreceivescriptmessage:(wkscriptmessage *)message{
 if ([message.name isequaltostring:@"showtime"]) {
  nslog(@"来了!");
 }
 nslog(@"message == %@ --- %@",message.name,message.body); 
}

// 最后在dealloc必须移除
[self.usercontentcontroller removescriptmessagehandlerforname:@"showtime"];
//如果是弹窗的必须自己实现代理方法
- (void)webview:(wkwebview *)webview runjavascriptalertpanelwithmessage:(nsstring *)message initiatedbyframe:(wkframeinfo *)frame completionhandler:(void (^)(void))completionhandler
{
 uialertcontroller *alert = [uialertcontroller alertcontrollerwithtitle:@"提醒" message:message preferredstyle:uialertcontrollerstylealert];
 [alert addaction:[uialertaction actionwithtitle:@"知道了" style:uialertactionstylecancel handler:^(uialertaction * _nonnull action) {
  completionhandler();
 }]];
 
 [self presentviewcontroller:alert animated:yes completion:nil];
}

一直用一直爽的交互

我们上面写了两者的一些交互,虽然可以用呢,但是没有带一种很简单很轻松的境界,所以有一个开源库:webviewjavascriptbridge。这个开源库可以同时兼容两者,而且交互很简单,但是你必须得前端一起,否则就哦豁了。

// 使用
self.wjb = [webviewjavascriptbridge bridgeforwebview:self.webview];
// 如果你要在vc中实现 uiwebview的代理方法 就实现下面的代码(否则省略)
[self.wjb setwebviewdelegate:self];

// 注册js方法名称
[self.wjb registerhandler:@"jscallsoc" handler:^(id data, wvjbresponsecallback responsecallback) {
 nslog(@"currentthread == %@",[nsthread currentthread]);
 nslog(@"data == %@ -- %@",data,responsecallback);
}];

// 调用js
dispatch_async(dispatch_get_global_queue(0, 0), ^{
  [self.wjb callhandler:@"occalljsfunction" data:@"oc调用js" responsecallback:^(id responsedata) {
   nslog(@"currentthread == %@",[nsthread currentthread]);
   nslog(@"调用完js后的回调:%@",responsedata);
  }];
});

前端使用实例如下,具体使用方法可以查看webviewjavascriptbridge

function setupwebviewjavascriptbridge(callback) {
	if (window.webviewjavascriptbridge) { return callback(webviewjavascriptbridge); }
	if (window.wvjbcallbacks) { return window.wvjbcallbacks.push(callback); }
	window.wvjbcallbacks = [callback];
	var wvjbiframe = document.createelement('iframe');
	wvjbiframe.style.display = 'none';
	wvjbiframe.src = 'https://__bridge_loaded__';
	document.documentelement.appendchild(wvjbiframe);
	settimeout(function() { document.documentelement.removechild(wvjbiframe) }, 0)
}

setupwebviewjavascriptbridge(function(bridge) {
	
	/* initialize your app here */

	bridge.registerhandler('js echo', function(data, responsecallback) {
		console.log("js echo called with:", data)
		responsecallback(data)
	})
	bridge.callhandler('objc echo', {'key':'value'}, function responsecallback(responsedata) {
		console.log("js received response:", responsedata)
	})
})

请求拦截

我们uiwebview在早期是使用- (bool)webview:(uiwebview *)webview shouldstartloadwithrequest:(nsurlrequest *)request navigationtype:(uiwebviewnavigationtype)navigationtype来根据scheme、host、pathcomponents进行拦截做自定义逻辑处理。但是这种方法不是很灵活,于是就使用nsurlprotocol来进行拦截,例如微信拦截淘宝一样,直接显示一个提示。又或者是拦截请求调用本地的接口,打开相机、录音、相册等功能。还能直接拦截后改变原有的request,直接返回数据或者其他的url,在一些去除广告时可以的用得上。

我们使用的时候必须要使用nsurlprotocol的子类来进行一些操作。并在使用前需要注册自定义的class。拦截后记得进行标记一下,防止自循环多执行。可惜的是在wkwebview中不能进行拦截后处理的操作,只能监听却改变不了。源于wkwebview采用的是webkit加载,和系统的浏览器一样的机制。

// 子类
@interface omurlprotocol : nsurlprotocol<nsurlsessiondatadelegate>
@property (nonatomic, strong) nsurlsession *session;
@end

// 注册
[nsurlprotocol registerclass:[omurlprotocol class]];
// 1. 首先会在这里来进行拦截,返回yes则表示需要经过我们自定义处理,no则走系统处理
+ (bool)caninitwithrequest:(nsurlrequest *)request;

// 2.拦截处理将会进入下一个环节, 返回一个标准化的request,可以在这里进行重定向
+ (nsurlrequest *)canonicalrequestforrequest:(nsurlrequest *)request;

// 3.是否成功拦截都会走这个方法, 可以在这里进行一些自定义处理
- (void)startloading;

// 4. 任何网络请求都会走上面的拦截处理,即使我们重定向后还会再走一次或多次流程,需要标记来处理
// 根据request获取标记值来决定是否需要拦截,在caninitwithrequest内处理
+ (nullable id)propertyforkey:(nsstring *)key inrequest:(nsurlrequest *)request;
// 标记
+ (void)setproperty:(id)value forkey:(nsstring *)key inrequest:(nsmutableurlrequest *)request;
// 移除标记
+ (void)removepropertyforkey:(nsstring *)key inrequest:(nsmutableurlrequest *)request;

请求头或数据混乱问题

还需要注意的一点是,如果实现线了拦截处理的话,我们在使用afn和urlsession进行访问的时候拦截会发现数据或请求头可能和你拦截处理后的数据或请求不符合预期,这是因为我们在拦截的时候只是先请求了a后请求了b,这是不符合预期的,虽然urlconnection不会但是已被废弃不值得提倡使用。我们通过在拦截的时候通过lldb打印session中配置的协议时,发现是这样的没有包含我们自定义的协议,我们通过runtime交换方法交换protocolclasses方法,我们实现我们自己的protocolclasses方法。但是为了保证系统原有的属性,我们应该在系统原有的协议表上加上我们的协议类。在当前我们虽然可以通过[nsurlsession sharedsession].configuration.protocolclasses;获取系统默认的协议类,但是如果我们在当前自定义的类里protocolclasses写的话会造成死循环,因为我们交换了该属性的getter方法。我们使用保存类名然后存储至nsuserdefaults,取值时在还原class。

po session.configuration.protocolclasses
<__nsarrayi 0x600001442d00>(
_nsurlhttpprotocol,
_nsurldataprotocol,
_nsurlftpprotocol,
_nsurlfileprotocol,
nsabouturlprotocol
)
// 自定义返回我们的协议类
- (nsarray *)protocolclasses {
 nsarray *originalprotocols = [omurlprotocol readoriginalprotocols];
 nsmutablearray *newprotocols = [nsmutablearray arraywitharray:originalprotocols];
 [newprotocols addobject:[omurlprotocol class]];
 return newprotocols;
}

// 我们再次打印时发现已经加上我们自定义的协议类了
po session.configuration.protocolclasses
<__nsarraym 0x60000041a4f0>(
_nsurlhttpprotocol,
_nsurldataprotocol,
_nsurlftpprotocol,
_nsurlfileprotocol,
nsabouturlprotocol,
omurlprotocol
)
// 存储系统原有的协议类
+ (void)saveoriginalprotocols: (nsarray<class> *)protocols{
 nsmutablearray *protocolnamearray = [nsmutablearray array];
 for (class protocol in protocols){
  [protocolnamearray addobject:nsstringfromclass(protocol)];
 }
 nslog(@"协议数组为: %@", protocolnamearray);
 [[nsuserdefaults standarduserdefaults] setobject:protocolnamearray forkey:originalprotocolskey];
 [[nsuserdefaults standarduserdefaults] synchronize];
}

// 获取系统原有的协议类
+ (nsarray<class> *)readoriginalprotocols{
 nsarray *classnames = [[nsuserdefaults standarduserdefaults] valueforkey:originalprotocolskey];
 nsmutablearray *origianlprotocols = [nsmutablearray array];
 for (nsstring *name in classnames){
  class class = nsclassfromstring(name);
  [origianlprotocols addobject: class];
 }
 return origianlprotocols;
}
+ (void)hooknsurlsessionconfiguration{
 nsarray *originalprotocols = [nsurlsession sharedsession].configuration.protocolclasses;
 [self saveoriginalprotocols:originalprotocols];
 class cls = nsclassfromstring(@"__nscfurlsessionconfiguration") ?: nsclassfromstring(@"nsurlsessionconfiguration");
 method originalmethod = class_getinstancemethod(cls, @selector(protocolclasses));
 method stubmethod = class_getinstancemethod([self class], @selector(protocolclasses));
 if (!originalmethod || !stubmethod) {
  [nsexception raise:nsinternalinconsistencyexception format:@"没有这个方法 无法交换"];
 }
 method_exchangeimplementations(originalmethod, stubmethod);
}

cookie的携带问题

很多应用场景中需要使用session来进行处理,在uiwebview中很容易做到携带这些cookie,但是由于wkwebview的机制不一样,跨域会出现丢失cookie的情况是很糟糕的。目前有两种用法:脚本和手动添加cookie。脚本不太靠谱,建议使用手动添加更为保险。

// 使用脚本来添加cookie

// 获取去cookie数据
- (nsstring *)cookiestring
{
 nsmutablestring *script = [nsmutablestring string];
 [script appendstring:@"var cookienames = document.cookie.split('; ').map(function(cookie) { return cookie.split('=')[0] } );\n"];
 for (nshttpcookie *cookie in [[nshttpcookiestorage sharedhttpcookiestorage] cookies]) {

  if ([cookie.value rangeofstring:@"'"].location != nsnotfound) {
   continue;
  }
  [script appendformat:@"if (cookienames.indexof('%@') == -1) { document.cookie='%@'; };\n", cookie.name, cookie.kc_formatcookiestring];
 }
 return script;
}

// 添加cookie
wkuserscript * cookiescript = [[wkuserscript alloc] initwithsource:[self cookiestring] injectiontime:wkuserscriptinjectiontimeatdocumentstart formainframeonly:no];
[[[wkusercontentcontroller alloc] init] adduserscript: cookiescript];
// 添加一个分类来修复cookie丢失的问题
@interface nsurlrequest (cookie)

- (nsurlrequest *)fixcookie;

@end

@implementation nsurlrequest (cookie)

- (nsurlrequest *)fixcookie{
 nsmutableurlrequest *fixedrequest;
 if ([self iskindofclass:[nsmutableurlrequest class]]) {
  fixedrequest = (nsmutableurlrequest *)self;
 } else {
  fixedrequest = self.mutablecopy;
 }
 //防止cookie丢失
 nsdictionary *dict = [nshttpcookie requestheaderfieldswithcookies:[nshttpcookiestorage sharedhttpcookiestorage].cookies];
 if (dict.count) {
  nsmutabledictionary *mdict = self.allhttpheaderfields.mutablecopy;
  [mdict setvaluesforkeyswithdictionary:dict];
  fixedrequest.allhttpheaderfields = mdict;
 }
 return fixedrequest;
}

@end
 
 
 // 使用场景
- (void)webview:(wkwebview *)webview decidepolicyfornavigationaction:(wknavigationaction *)navigationaction decisionhandler:(void (^)(wknavigationactionpolicy))decisionhandler {
 [navigationaction.request fixcookie];
 decisionhandler(wknavigationactionpolicyallow);
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网