Enable Cookies in UIWebView

核能气质少年 提交于 2019-12-08 23:59:13

问题


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


回答1:


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.



回答2:


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)



来源:https://stackoverflow.com/questions/9794999/enable-cookies-in-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!