5
votes

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?

1

1 Answers

2
votes

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