Question

I am setting (or attempting to set) an NSHTTPCookie as follows:

+ (void)setCookie {

  NSString* cookieName = @"MyCookieName";
  NSString* cookieValue = @"MyCookieValue";
  NSString* cookieOriginURL = @"www.mycompany.com";
  NSString* cookiePath = @"/";

  NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
  [cookieProperties setObject:cookieName      forKey:NSHTTPCookieName];
  [cookieProperties setObject:cookieValue     forKey:NSHTTPCookieValue];
  [cookieProperties setObject:cookieOriginURL forKey:NSHTTPCookieOriginURL];
  [cookieProperties setObject:cookiePath      forKey:NSHTTPCookiePath];

  [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:3600] forKey:NSHTTPCookieExpires];

  NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
  [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

}

After this method is called, I create an NSURLRequest:

NSString *urlAddress = @"http//:www.mycompany.com/mobile/home";

//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];

//URL Request Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

NSLog(@"Here's the request: %@", [requestObj description]);

//Load the request in the UIWebView.
[self.webView loadRequest:requestObj];

But the output is:

Here's the request: <NSURLRequest: 0xa33a4d0> { URL: http:www.mycompany.com/mobile/home

I expected to see the cookie info appended to the request, but it is not.

I don't know much about cookies, so I don't know if my code is missing something, or if I'm just miss interpreting what the output means.

Thanks for any help.

Was it helpful?

Solution

I doubt that the description of the NSURLRequest will provide the cookie information.

The domains are a match (cookie and the URL), so the cookie must be appended to the request. Execute the following code before firing the request to see which cookies are sent along with your request.

NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for(NSHTTPCookie *cookie in [cookieJar cookiesForURL:url]) {
        NSLog(@"Cookies attached: %@", cookie.description);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top