gpt4 book ai didi

ios - 与 UIWebView 共享 WKWebView Cookie

转载 作者:行者123 更新时间:2023-11-30 12:33:28 25 4
gpt4 key购买 nike

我正在尝试与 UIWebView 共享 WKWebView Cookie 以获取所有 cookie。我知道与 WKWebView 相比,从 UIWebView 获取所有 cookie 非常简单。

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

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 登录我的帐户时使用上面的代码,UiWe​​bView 还没有登录我。我还尝试与 WKWebView 共享 UIWebView Cookie,并且成功了。

请问谁能告诉我如何与 UIWebView 共享 WKWebView Cookie 或如何从 WKWebView 获取所有 Cookie?

谢谢

最佳答案

您需要按照以下步骤设置wkwebview cookie

初始化中首先是执行设置Cookies的脚本:

-(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 header :

- (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
}

关于ios - 与 UIWebView 共享 WKWebView Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43154918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com