UIWebview启用cookie

我试图通过UIWebView访问需要cookie的特定URL,但由于禁用了cookie,我无法访问它。 所以我做了以下几点:

  • 启用Cookie:

     NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways]; 
  • 创buildNSURLConnection并从响应中提取cookie:

     NSArray *cookies = [ NSHTTPCookie cookiesWithResponseHeaderFields: [ httpResponse allHeaderFields ] forURL:response.URL]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies: cookies forURL: response.URL mainDocumentURL:nil]; 

但是这两者都没有帮助。 但是,如果我在safari中启动URL,则会成功加载,之后我可以在UIWebView加载相同的URL。 你能帮我这个,我怎么能启用cookie的UIWebView

提前致谢

创buildNSURLRequest ,将sharedHTTPCookieStorage中的所有cookie复制到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"]; } } }