Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ios - when redirect with code 302, WKWebView cannot set cookie

I sent request to url1. url1 will redirect to url2 with cookie. url2 is for authorization. And I get code "302 found", which is correct. But when url2 redirect back to url1, the cookie lost. This results my request keeping redirect to url2, looping until failed.

Does any one met this kind of problem and know a solution? Thanks in advance.

This is a WKWebView problem. UIWebView will work fine. But somehow, I need to change to use WKWebView.

I already tried many solutions, such as Can I set the cookies to be used by a WKWebView?. These methods could handle the cookie in same domain. My problem is url1 and url2 have different domains. When redirect, the cookie is missing, which made the authorization failed, and resulted in looping between url1 and url2.

Does anybody met this problem and found out a workaround? Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Unfortunately, there is no official support for handling 302 redirect response in WKWebView.I came across the same issue too.There is a way to work around but may take some risks and not elegant.

  1. Override the WKWebView.load(_ request: URLRequest) and use URLSession to make the request instead.
  2. Make sure your URLSession can deal with 302 redirect by yourself which means you need to implement func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) to specify that you don't want the URLSession to handle 302 redirect automatically.
  3. Once you get the 302 response using URLSession the attached cookie will be set to HTTPCookieStorage.shared automatically.And then make a new request with those cookies and the url of response header field Location by WKWebView itself.

The code sample is Here.I subclass WKWebView and also deal with cookies in the most case including your 302 redirect case.If it works for you, please give me a star thx!

It is a really a hack way and be careful if you want use it in product.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...