2017-04-01 117 views
0

我试图与UIWebView共享WKWebView饼干获取所有cookie。我知道它很容易从UIWebView获取所有cookie,比较WKWebView。与UIWebView共享WKWebView饼干

我在选项卡式应用程序模板中创建两个WebView(WKWebView,UIWebView)。下面的方法,我用于与UIWebView共享WKWebView饼干,但没有得到成功。

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { 

    let response = navigationResponse.response as? HTTPURLResponse 
    let cookies = HTTPCookie.cookies(withResponseHeaderFields: response?.allHeaderFields as! [String : String], for: (response?.url)!) 

    HTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.always 

    for cookie in cookies { 
    HTTPCookieStorage.shared.setCookie(cookie) 
    } 

    decisionHandler(WKNavigationResponsePolicy.allow); 
} 

使用上面的代码,当我登录到我的帐户从WKWebView,UIWebView中没有登录我了。 我也尝试与WKWebView共享UIWebView饼干,它工作。

请任何人都可以告诉我如何与UIWebView共享WKWebView饼干或如何从WKWebView获取所有cookie?

感谢

回答

0

您需要按照以下初始化以下

第一步骤设置wkwebview饼干是执行脚本设置的Cookie:

-(void)initWebView 
{ 
    WKWebViewConfiguration *webViewconfiguration = [[WKWebViewConfiguration alloc] init]; 
    WKUserContentController *wkUController = [[WKUserContentController alloc] init]; 
    if(URL.host hasSuffix:baseDomain){ 
    //Here to determine whether the domain name is their own website 
     NSString *jScript = [self setCookies]; 
     WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO]; 
        [wkUController addUserScript:wkUScript]; 
} 
    webViewconfiguration.userContentController = wkUController; 
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, width, height) configuration:webViewconfiguration]; 
} 
//The script that executes may be slightly different 
+(NSString *)setCookies 
{ 
    NSString *script = [NSString string]; 

    for (NSHTTPCookie *httpCookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) 
    { 
     NSString *cookie = [NSString stringWithFormat:@"%@=%@;domain=%@;path=%@",httpCookie.name,httpCookie.value,httpCookie.domain,httpCookie.path?:@"/"]; 
     script = [script stringByAppendingString:[NSString stringWithFormat:@"document.cookie='%@';",cookie]]; 

    } 
    return script; 
} 

,然后手动添加在创建NSURLRequest对象时,将Cookie添加到HTTP的标题中:

- (void)loadRequest:(NSURLRequest *)request 
{ 
    //Here to determine whether the domain name is their own website 
    if ([request.URL.host hasSuffix:baseDomain]){ 
     NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:request.URL]; 
     NSString *cookies = @""; //setting Cookies 
     [mutableRequest addValue:cookies forHTTPHeaderField:@"Cookie"]; 
} 
    // do request 
}