Sunday, June 16, 2013

NSHTTPCookieStorage cookiesForURL example in Objective C (iOS).


NSHTTPCookieStorage cookiesForURL

Returns all the cookie storage’s cookies that are sent to a specified URL.

- (NSArray *)cookiesForURL:(NSURL *)theURL

Parameters of [NSHTTPCookieStorage cookiesForURL]
theURL
The URL to filter on.

Return Value
An array of cookies whose URL matches the provided URL.

Discussion of [NSHTTPCookieStorage cookiesForURL]
An application can use NSHTTPCookie method requestHeaderFieldsWithCookies: to turn this array into a set of header fields to add to an NSMutableURLRequest object.

NSHTTPCookieStorage cookiesForURL example.
first check if

[[NSHTTPCookieStorage sharedHTTPCookieStorage]
    cookiesForURL:[NSURL URLWithString:theCookie]]
returns what you think it should return. If not, take a closer look at the value of theCookie.

Example of [NSHTTPCookieStorage cookiesForURL].
- ( void )reloadWebview: (id)sender
{
    NSArray                 *cookies;
    NSDictionary            *cookieHeaders;
    NSMutableURLRequest     *request;

    cookies = [[ NSHTTPCookieStorage sharedHTTPCookieStorage ]
                cookiesForURL: self.url ];
    if ( !cookies ) {
        /* kick off new NSURLConnection to retrieve new auth cookie */
        return;
    }

    cookieHeaders = [ NSHTTPCookie requestHeaderFieldsWithCookies: cookies ];
    request = [[ NSMutableURLRequest alloc ] initWithURL: self.url ];
    [ request setValue: [ cookieHeaders objectForKey: @"Cookie" ]
              forHTTPHeaderField: @"Cookie" ];

    [ self.webView loadRequest: request ];
    [ request release ];
}

NSHTTPCookieStorage cookiesForURL example.
    NSHTTPURLResponse   * response;
    NSError             * error;
    NSMutableURLRequest * request;
    request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://temp/gomh/authenticate.py?setCookie=1"]
                                            cachePolicy:NSURLRequestReloadIgnoringCacheData
                                        timeoutInterval:60] autorelease];

    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    NSLog(@"RESPONSE HEADERS: \n%@", [response allHeaderFields]);

    // If you want to get all of the cookies:
    NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@"http://temp"]];
    NSLog(@"How many Cookies: %d", all.count);
    // Store the cookies:
    // NSHTTPCookieStorage is a Singleton.
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:all forURL:[NSURL URLWithString:@"http://temp"] mainDocumentURL:nil];

    // Now we can print all of the cookies we have:
    for (NSHTTPCookie *cookie in all)
        NSLog(@"Name: %@ : Value: %@, Expires: %@", cookie.name, cookie.value, cookie.expiresDate);

    // Now lets go back the other way.  We want the server to know we have some cookies available:
    // this availableCookies array is going to be the same as the 'all' array above.  We could
    // have just used the 'all' array, but this shows you how to get the cookies back from the singleton.
    NSArray * availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"http://temp"]];
    NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies];

    // we are just recycling the original request
    [request setAllHTTPHeaderFields:headers];

    request.URL = [NSURL URLWithString:@"http://temp/gomh/authenticate.py"];
    error       = nil;
    response    = nil;

    NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"The server saw:\n%@", [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease]);

End of NSHTTPCookieStorage cookiesForURL example article.