2017-04-01 91 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 
}