Enable Cookies in UIWebView

2020-02-29 01:56发布

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

2条回答
Explosion°爆炸
2楼-- · 2020-02-29 02:44

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)

查看更多
冷血范
3楼-- · 2020-02-29 02:52

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.
查看更多
登录 后发表回答