如何在 Objective-C 中要求用户接受或拒绝 WKWebView 网站的 cookie
Posted
技术标签:
【中文标题】如何在 Objective-C 中要求用户接受或拒绝 WKWebView 网站的 cookie【英文标题】:How to ask users to accept or deny cookies for WKWebView website in Objective-C 【发布时间】:2020-11-10 22:12:21 【问题描述】:试图要求用户在 ios 的 WKWebView 中接受具有目标 C 的 3rd 方 cookie。这是我当前的代码:
-(void) viewDidLoad
[super viewDidLoad];
webView = [[WKWebView alloc] initWithFrame:[[self view] bounds]];
NSURL *url = [NSURL URLWithString:@"https://www.example.com"];
NSURLRequest *urlReq = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlReq];
[self.view addSubview:webView];
[self setupConfiguration];
// Do any additional setup after loading the view.
很抱歉,这不是一个狭隘的问题 - 接近截止日期并需要帮助,并且对于 Objective-c/iOS 来说仍然相对较新。非常感谢任何帮助!
【问题讨论】:
【参考方案1】:您必须按照<WKNavigationDelegate>
协议声明您的 ViewControllers 接口
并实施
-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
NSHTTPURLResponse *response = (NSHTTPURLResponse*)navigationResponse.response;
NSURL *url = response.URL;
if (!url)
decisionHandler(WKNavigationResponsePolicyCancel);
return;
NSDictionary<NSString *, NSString *> *headerFields = response.allHeaderFields;
if (headerFields.count > 0)
NSArray<NSHTTPCookie *> *cookielist = [NSHTTPCookie cookiesWithResponseHeaderFields:headerFields forURL:url];
for (NSHTTPCookie *cookie in cookielist)
[_webView.configuration.websiteDataStore.httpCookieStore setCookie:cookie completionHandler:nil];
decisionHandler(WKNavigationResponsePolicyAllow);
-(void)setupConfiguration
//this is actually the old way, but is not deprecated.
NSHTTPCookieStorage *appCookies = NSHTTPCookieStorage.sharedHTTPCookieStorage;
appCookies.cookieAcceptPolicy = NSHTTPCookieAcceptPolicyAlways;
//... your stuff ...
【讨论】:
NSHTTPCookieStorage 真的可以在 WKWebView 上工作吗?认为它总是用于 UIWebView RFC 6265 仍然是标准,因此其存储策略仍然有效。仔细阅读如果触发设备策略、应用程序策略和基于视图的策略会发生什么。请参阅:NSHTTPCookieStorage 与 WKHTTPCookieStore。特别注意In cases where a cookie storage is shared between processes, changes made to the cookie accept policy affect all currently running apps using the cookie storage.
观看文档以了解 可用性以上是关于如何在 Objective-C 中要求用户接受或拒绝 WKWebView 网站的 cookie的主要内容,如果未能解决你的问题,请参考以下文章