Jiwoo  Choi Jiwoo Choi - 2 months ago 52
iOS Question

How to get cookie from WKwebview (IOS)

I'd like to receive a cookie containing login status through WKwebview.

what I finally want is receiving that cookie data, parsing them,and then changing the view for the user logged in.

What I've tired :
webview.evaluateJavascript("document.cookie.search('LoginSession=Y')") { (data,error) -> .....
}

result : if the data is 'data >= 1', login status(a variable in IOS app) = true, but under 0(data < 0),login status will be false.

and it works like a charm seemingly for my app.

However, This way looks very a physical and simple way, so I think, it could be not secure for some users, and It might have no guarantee for working perfectly for all environments with IOS.

Q1 : Is it not dangerous way?

Q2 : I've heard that IOS stores the cookies in Memory unlike other platforms, and we could manage to load the cookie data from Memory through some codes. Are there any recommended libraries for developers to handle cookies from WKWEB?

Answer

Courtesy : Siyu Song's Answer

You can have access to an NSHTTPURLResponse object in - webView:decidePolicyForNavigationResponse:decisionHandler: method defined on WKNavigationDelegate. You can later extract the cookies manually from the HTTP header:

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@""]];
    for (NSHTTPCookie *cookie in newCookies) {
        // Do something with the cookie
    }

    decisionHandler(WKNavigationResponsePolicyAllow);
}

Please post your solution if you have a better one.

Comments