4

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:

  • Enabled cookies:

    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    
  • 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];
    

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?

Thanks in advance

Rob
  • 371,891
  • 67
  • 713
  • 902
leon4ic
  • 339
  • 4
  • 12

1 Answers1

6

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];

And add addCookies:forRequest method

- (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"];
        }
    }
}
OpenThread
  • 2,076
  • 3
  • 27
  • 49