現(xiàn)在app大多由h5頁(yè)面展示蟋定,我們使用wkwebivew代替uiwebview,減少了內(nèi)存占用草添,但同時(shí)也有些坑,下面羅列我遇到的坑:
1溢吻、wkwebiew cookie丟失
在h5跳轉(zhuǎn)h5時(shí),cookie會(huì)丟失果元,導(dǎo)致登錄無(wú)效促王。解決方法:
- (void)webView:(WKWebView*)webView didFinishNavigation:(null_unspecifiedWKNavigation*)navigation {
NSHTTPCookieStorage*cookieStorage = [NSHTTPCookieStoragesharedHTTPCookieStorage];
//js函數(shù)
NSString*JSFuncString =
@"function setCookie(name,value,expires)\
{\
var oDate=new Date();\
oDate.setDate(oDate.getDate()+expires);\
document.cookie=name+'='+value+';expires='+oDate+';path=/'\
}\
function getCookie(name)\
{\
var arr = document.cookie.match(new RegExp('(^| )'+name+'=({FNXX==XXFN}*)(;|$)'));\
if(arr != null) return unescape(arr[2]); return null;\
}\
function delCookie(name)\
{\
var exp = new Date();\
exp.setTime(exp.getTime() - 1);\
var cval=getCookie(name);\
if(cval!=null) document.cookie= name + '='+cval+';expires='+exp.toGMTString();\
}";
//拼湊js字符串
NSMutableString*JSCookieString = JSFuncString.mutableCopy;
for(NSHTTPCookie*cookieincookieStorage.cookies) {
NSString*excuteJSString = [NSStringstringWithFormat:@"setCookie('%@', '%@', 1);", cookie.name, cookie.value];
[JSCookieStringappendString:excuteJSString];
}
//執(zhí)行js
[webViewevaluateJavaScript:JSCookieStringcompletionHandler:^(idobj,NSError*_Nullableerror) {
NSLog(@"%@",error);
}];
2、白屏問(wèn)題:
當(dāng)內(nèi)存占用過(guò)多時(shí)而晒,會(huì)出現(xiàn)白屏問(wèn)題蝇狼,找了好久的解決方法:嘗試的方法
1)判斷webview的title是否存在,不存在重新加載:
if(_webview.title==nil) {
[_webviewreload];
}
然后加上這個(gè)方法還是會(huì)出現(xiàn)白屏倡怎,所以嘗試下面的解決方法:
2)判斷webview body是否存在
[webviewevaluateJavaScript:@"document.querySelector('body').innerHTML"completionHandler:^(idresult,NSError*error) {
if(!result || ([resultisKindOfClass:[NSStringclass]] && [((NSString*)result)length] ==0)) {
[webviewreload];
}
}];
這個(gè)方法加上目前還沒(méi)測(cè)出白屏迅耘。??