iOS8之后有了WKWebView,相信都知道WKWebView比UIWebView性能好很多,然而真正用起来,你会发现WKWebView各种坑...比如同步Cookie,JS-OC的相互调用,我曾经有几次想换回UIWebView,网上看了各种关于WKWebView的,发现很多最终都换回了UIWebView...
本文章是参照简友 Caiflower WKWebView之同步Cookie - WKWebView踩坑记录 给自己做个记录,解决在push出新的WKWebView页面的时候无法共用一个Cookie的问题
WKWebView有自己的缓存机制,如果想同步session需要注意
1.使用全局的processPool
@interface XXWebKitSupport : NSObject
@property (nonatomic, strong,readonly) WKProcessPool *processPool;
+ (instancetype)sharedSupport;
@end
@interface XXWebKitSupport ()
@property (nonatomic, strong) WKProcessPool *processPool;
@end
@implementation XXWebKitSupport
+ (instancetype)sharedSupport {
static XXWebKitSupport *_instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [XXWebKitSupport new]; });
return _instance;
}
- (instancetype)init {
if (self = [super init]) {
self.processPool = [WKProcessPool new];
}
return self;
}
2.在ViewController页面中初始化WKWebView
- (WKWebView *)myWebView {
if (_myWebView == nil) {
WKUserContentController* userContentController = [WKUserContentController new]; NSMutableString *cookies = [NSMutableString string];
WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:[cookies copy] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO]; [userContentController addUserScript:cookieScript];
WKWebViewConfiguration *configuration = [WKWebViewConfiguration new]; // 设置偏好设置 configuration.preferences = [[WKPreferences alloc] init]; // 默认为0 configuration.preferences.minimumFontSize = 10; // 默认认为YES configuration.preferences.javaScriptEnabled = YES; // 在iOS上默认为NO,表示不能自动通过窗口打开
configuration.preferences.javaScriptCanOpenWindowsAutomatically = NO;
// web内容处理池 // 全局使用同一个processPool
configuration.processPool = [[XXWebKitSupport sharedSupport] processPool];
//注册回调 JS -> OC
[userContentController addScriptMessageHandler:self name:@"showSendMsg"];
[userContentController addScriptMessageHandler:self name:@"onOrderStart"];
[userContentController addScriptMessageHandler:self name:@"shopAppTitle"]; [userContentController addScriptMessageHandler:self name:@"onClose"]; [userContentController addScriptMessageHandler:self name:@"setBarTitle"]; configuration.userContentController = userContentController;
WKWebView *webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, kDeviceWidth, KDeviceHeight -SafeAreaTopHeight)configuration:configuration]; webView.navigationDelegate = self;
webView.scrollView.scrollEnabled = YES;
webView.backgroundColor = CCCUIColorFromHex(0xf7f7f7);
// 允许左右划手势导航,默认允许
webView.allowsBackForwardNavigationGestures = YES;
_myWebView = webView;
[self.myWebView setValue:[NSValue valueWithUIEdgeInsets:self.myWebView.scrollView.contentInset] forKey:@"_obscuredInsets"];
}
return _myWebView;
}
3.在WKNavigationDelegate代理方法中将Cookie设置到本地
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(
WKNavigationResponsePolicy))decisionHandler{
NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response; // 获取cookie,并设置到本地
NSArray *cookies =[NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
for (NSHTTPCookie *cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
decisionHandler(WKNavigationResponsePolicyAllow);
}
4.在WKWebView加载请求的时候注入Cookie
NSMutableString *cookies = [NSMutableString string];
NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:_reqString cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
// 一般都只需要同步JSESSIONID,可视不同需求自己做更改
NSString * JSESSIONID;
// 获取本地所有的Cookie
NSArray *tmp = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
for (NSHTTPCookie * cookie in tmp) {
if ([cookie.name isEqualToString:@"JSESSIONID"]) {
JSESSIONID = cookie.value;
break;
}
}
if (JSESSIONID.length) {
// 格式化Cookie
[cookies appendFormat:@"JSESSIONID=%@;",JSESSIONID];
}
// 注入Cookie
[requestObj setValue:cookies forHTTPHeaderField:@"Cookie"];
// 加载请求
[self.myWebView loadRequest:requestObj];
经过以上几步已经可以同步Cookie了。
网上查过很多资料具体还是要是自己本身项目情况而定
网友评论