在UIWebView中启用Cookie

时间:2012-03-20 21:08:53

标签: ios iphone cookies ios5 uiwebview

如何在使用UIWebView窗口的iPhone应用程序中启用cookie,以便我的登录系统能够正常工作?

2 个答案:

答案 0 :(得分:9)

一定要从

开始
[NSHTTPCookieStorage sharedHTTPCookieStorage].cookieAcceptPolicy = 
    NSHTTPCookieAcceptPolicyAlways;

但是,如@JoelFan所述,问题可能是您的用户代理字符串导致ASP.NET在无cookie登录时尝试失败。而不是包含

的响应
  

Set-Cookie:.ASPXAUTH = 真正的长十六进制数

它返回重定向到

之类的东西
  

位置:/(F( long-sorta-base64ish-looking-string ))/

默认的UIWebView用户代理字符串类似于

  

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

但ASP.NET不喜欢这个。 Safari发送的内容如下:

  

User-Agent:Mozilla / 5.0(iPad; CPU OS 7_0_2,如Mac OS X)AppleWebKit / 537.51.1(KHTML,与Gecko一样)版本/ 7.0 移动/ 11A501 Safari / 9537.53

请尽早在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.

答案 1 :(得分:1)

如果您登录的站点是ASP.NET站点,则问题可能是由于UIWebView发送了无法识别的用户代理。见Change User Agent in UIWebView (iPhone SDK)