Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable Cookies in UIWebView

How can I enable cookies in my iPhone Application that uses a UIWebView Window, so that my login system will work?

like image 531
e__ Avatar asked Mar 20 '12 21:03

e__


2 Answers

For sure start with

[NSHTTPCookieStorage sharedHTTPCookieStorage].cookieAcceptPolicy = 
    NSHTTPCookieAcceptPolicyAlways;

But, as mentioned by @JoelFan, the issue may be your User Agent string causing ASP.NET to attempt and fail at a cookieless login. Instead of a response that includes

Set-Cookie: .ASPXAUTH=really-long-hex-number

it returns a redirection to something like

Location: /(F(long-sorta-base64ish-looking-string))/

The default UIWebView user agent string is something like

User-Agent: Mozilla/5.0 (iPad; CPU OS 7_0_2 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/11A501

but ASP.NET doesn't like this. Safari sends something like this:

User-Agent: Mozilla/5.0 (iPad; CPU OS 7_0_2 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A501 Safari/9537.53

Do the following early on, maybe in your AppDelegate.m

// DON'T try to reuse a UIWebView for this. 
UIWebView *wv = [[UIWebView alloc] initWithFrame:CGRectZero];
// This webview has already decided to use the default user agent string.

// let's use javascript to get the existing user agent string
NSString *userAgent = [wv stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

// let's tack on some stuff to make ASP.NET happy
userAgent = [userAgent stringByAppendingString:@" Version/7.0 Safari/9537.53"];

[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
// New UIWebViews inited after here will use the user agent string you made.
like image 173
Hafthor Avatar answered Sep 19 '22 12:09

Hafthor


If the site you are logging into is an ASP.NET site, the problem may be due to the UIWebView sending an unrecognized User Agent. See Change User Agent in UIWebView (iPhone SDK)

like image 24
JoelFan Avatar answered Sep 18 '22 12:09

JoelFan