UIWebview enable cookies(UIWebview 启用cookies)
问题描述
我正在尝试通过 UIWebView
访问需要 cookie 的特定 URL,但我无法访问它,因为 cookie 被禁用.所以我做了以下事情:
I am trying to access a specific URL that requires cookies through UIWebView
but I can not access it because cookies are disabled. So I did the following:
启用 cookie:
Enabled cookies:
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
[cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
创建 NSURLConnection
并从响应中提取 cookie:
Created NSURLConnection
and extracted cookies from response:
NSArray *cookies = [ NSHTTPCookie cookiesWithResponseHeaderFields: [ httpResponse allHeaderFields ] forURL:response.URL];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies: cookies forURL: response.URL mainDocumentURL:nil];
但这都没有帮助.但是,如果我在 safari 中启动 URL,它会成功加载,之后我也可以在 UIWebView
中加载相同的 URL.你能帮我解决这个问题,我怎样才能为 UIWebView
启用 cookie?
But neither of this didn't help. However if I launch the URL in safari it loads successfully and after that I can load the same URL in UIWebView
too. Could you help me with this, how can I enable cookies for UIWebView
?
提前致谢
推荐答案
创建NSURLRequest
后,将sharedHTTPCookieStorage中的所有cookie复制到NSURLRequest
:
After create a NSURLRequest
, copy all cookies in sharedHTTPCookieStorage to NSURLRequest
:
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPShouldHandleCookies:YES];
[self addCookies:cookies forRequest:request];
[_webView loadRequest:request];
并添加addCookies:forRequest
方法
- (void)addCookies:(NSArray *)cookies forRequest:(NSMutableURLRequest *)request
{
if ([cookies count] > 0)
{
NSHTTPCookie *cookie;
NSString *cookieHeader = nil;
for (cookie in cookies)
{
if (!cookieHeader)
{
cookieHeader = [NSString stringWithFormat: @"%@=%@",[cookie name],[cookie value]];
}
else
{
cookieHeader = [NSString stringWithFormat: @"%@; %@=%@",cookieHeader,[cookie name],[cookie value]];
}
}
if (cookieHeader)
{
[request setValue:cookieHeader forHTTPHeaderField:@"Cookie"];
}
}
}
这篇关于UIWebview 启用cookies的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:UIWebview 启用cookies


- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- URL编码Swift iOS 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- UITextView 内容插图 2022-01-01