0

Trying to ask users to accept 3rd party cookies with objective C in WKWebView for iOS. Here's my current code:

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

Sorry if this isn't a narrow question - running close to a deadline and need help and still relatively new to objective-c/iOS. Any help is much appreciated!

1 Answers1

0

you will have to declare your ViewControllers interface following the <WKNavigationDelegate> Protocol

and implement

-(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 ...
}
Ol Sen
  • 3,163
  • 2
  • 21
  • 30
  • Does NSHTTPCookieStorage actually work on WKWebView? thought it's always for UIWebView – Hammerhead Feb 04 '21 at 09:45
  • 1
    RFC 6265 is still the standard and so its storage policy are still valid. Read careful what happens if device policy, app policy and view based policies are triggered. See: [NSHTTPCookieStorage](https://developer.apple.com/documentation/foundation/nshttpcookiestorage) vs [WKHTTPCookieStore](https://developer.apple.com/documentation/webkit/wkhttpcookiestore?language=objc). Specially the Note `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.` Watch documentations for **Availability** – Ol Sen Feb 04 '21 at 20:38