我正在try 将现有的应用程序从UIWebView
切换到WKWebView
.当前APP管理webview
之外的用户登录/会话,并将认证所需的cookies
设置到NSHTTPCookieStore
中.不幸的是,新WKWebView
没有使用NSHTTPCookieStorage
中的cookies
.有没有其他方法可以做到这一点呢?
我正在try 将现有的应用程序从UIWebView
切换到WKWebView
.当前APP管理webview
之外的用户登录/会话,并将认证所需的cookies
设置到NSHTTPCookieStore
中.不幸的是,新WKWebView
没有使用NSHTTPCookieStorage
中的cookies
.有没有其他方法可以做到这一点呢?
Edit for iOS 11+ only
let cookie = HTTPCookie(properties: [
.domain: "example.com",
.path: "/",
.name: "MyCookieName",
.value: "MyCookieValue",
.secure: "TRUE",
.expires: NSDate(timeIntervalSinceNow: 31556926)
])!
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
由于您要将它们从HTTPCookeStorage拉过来,因此可以执行以下操作:
let cookies = HTTPCookieStorage.shared.cookies ?? []
for cookie in cookies {
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
}
Old answer for iOS 10 and below
如果您需要在初始加载请求上设置cookie,可以在NSMutableURLRequest上设置它们.因为Cookie只是一个特殊格式化的请求头,所以可以这样实现:
WKWebView * webView = /*set up your webView*/
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/index.html"]];
[request addValue:@"TeskCookieKey1=TeskCookieValue1;TeskCookieKey2=TeskCookieValue2;" forHTTPHeaderField:@"Cookie"];
// use stringWithFormat: in the above line to inject your values programmatically
[webView loadRequest:request];
如果需要页面上的后续AJAX请求设置cookie,只需在文档开始时使用WKUserScript通过javascript编程设置值即可实现,如下所示:
WKUserContentController* userContentController = WKUserContentController.new;
WKUserScript * cookieScript = [[WKUserScript alloc]
initWithSource: @"document.cookie = 'TeskCookieKey1=TeskCookieValue1';document.cookie = 'TeskCookieKey2=TeskCookieValue2';"
injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
// again, use stringWithFormat: in the above line to inject your values programmatically
[userContentController addUserScript:cookieScript];
WKWebViewConfiguration* webViewConfig = WKWebViewConfiguration.new;
webViewConfig.userContentController = userContentController;
WKWebView * webView = [[WKWebView alloc] initWithFrame:CGRectMake(/*set your values*/) configuration:webViewConfig];
将这两种技术结合起来,应该可以为您提供足够的工具,将cookie值从本机应用程序区转移到Web视图区.如果你需要更高级的cookie,你可以在cookie javascript API on Mozilla's page上找到更多信息.
是的,苹果不支持the niceties of UIWebView个中的很多个,这真是太糟糕了.我不确定他们是否会支持他们,但希望他们很快就能做到这一点.希望这能有所帮助!