Skip to content

Commit ef6754d

Browse files
committed
Sync cookies with WKWebView
1 parent bffcc8d commit ef6754d

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

src/ios/IONAssetHandler.m

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,22 +42,39 @@ - (void)webView:(WKWebView *)webView startURLSchemeTask:(id <WKURLSchemeTask>)ur
4242
loadFile = false;
4343
startPath = [stringToLoad stringByReplacingOccurrencesOfString:@"/_http_proxy_" withString:@"http://"];
4444
//startPath = [stringToLoad stringByReplacingOccurrencesOfString:@"/_https_proxy_" withString:@"https://"];
45-
NSLog(@"Proxy %@", startPath);
4645
NSURL * requestUrl = [NSURL URLWithString:startPath];
46+
WKWebsiteDataStore* dataStore = [WKWebsiteDataStore defaultDataStore];
47+
WKHTTPCookieStore* cookieStore = dataStore.httpCookieStore;
4748
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
4849
[request setHTTPMethod:method];
4950
[request setURL:requestUrl];
5051
if (body) {
5152
[request setHTTPBody:body];
5253
}
5354
[request setAllHTTPHeaderFields:header];
54-
//[request setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies]];
5555
[request setHTTPShouldHandleCookies:YES];
5656

5757
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
5858
if(error) {
5959
NSLog(@"Proxy error: %@", error);
6060
}
61+
62+
// set cookies to WKWebView
63+
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
64+
NSArray* cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[httpResponse allHeaderFields] forURL:response.URL];
65+
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:httpResponse.URL mainDocumentURL:nil];
66+
cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
67+
68+
for (NSHTTPCookie* c in cookies)
69+
{
70+
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
71+
//running in background thread is necessary because setCookie otherwise fails
72+
dispatch_async(dispatch_get_main_queue(), ^(void){
73+
NSLog(@"sync cookie: %@", c.name);
74+
[cookieStore setCookie:c completionHandler:nil];
75+
});
76+
});
77+
};
6178

6279
[urlSchemeTask didReceiveResponse:response];
6380
[urlSchemeTask didReceiveData:data];

0 commit comments

Comments
 (0)