Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to read cookie in UIWebview browser with document.cookie

I have an iOS app where I am loading html content inside a webview. The html is a login page wherein the user credentials are sent to the server via ajax and an authentication success/failure response is received. Now, the response contains a cookie (in the Set-Cookie header field) which I can capture on the Objective-C side like so,

NSDictionary* headers = [(NSHTTPURLResponse *)response allHeaderFields]; 
NSString *strCookies = [headers valueForKey:@"Set-Cookie"]; 
NSLog(@"cookies -> %@", strCookies);

The same response also contains a responseText which I use inside the browser:

Ajax("/login", "POST", { onsuccess : function(response){ 
       /* Do HTML stuff with response */ }  
});

Now I need the cookie to make further ajax requests (after the login page). However, the cookie is not set inside the webview browser. Looking for document.cookie returns an empty string. I can print all the response headers using xhr.getAllResponseHeaders() but I cannot access the Set-Cookie field in the xhr object.

How can the cookie be set inside the webview? Or I have no choice but to make all ajax requests via Obj-C?

like image 885
fenderplayer Avatar asked Nov 05 '22 03:11

fenderplayer


1 Answers

You can set the cookie in the request that you send to the webview.

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:yourURL];
[request setValue:yourCookie forHTTPHeaderField:@"Cookie"];

This could be done in the UIWebview delegate shouldStartLoadWithRequest

like image 185
oiledCode Avatar answered Nov 10 '22 06:11

oiledCode