Wednesday, June 12, 2013

NSHTTPCookie cookieWithProperties example in Objective C (iOS).

NSHTTPCookie cookieWithProperties

Creates and initializes an NSHTTPCookie object using the provided properties.

+ (id)cookieWithProperties:(NSDictionary *)properties

Parameters of [NSHTTPCookie cookieWithProperties]
properties
The properties for the new cookie object, expressed as key value pairs.

Return Value
The newly created cookie object. Returns nil if the provided properties are invalid.

Discussion of [NSHTTPCookie cookieWithProperties]
See “Constants” for more information on the available header field constants and the constraints imposed on the values in the dictionary.

NSHTTPCookie cookieWithProperties example.
This is how you set properties in a cookie:

 NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
                              url, NSHTTPCookieOriginURL,
                              @"testCookies", NSHTTPCookieName,
                              @"1", NSHTTPCookieValue,
                              nil];
  NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];

Example of [NSHTTPCookie cookieWithProperties].
NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"domain.com", NSHTTPCookieDomain,
                            @"\\", NSHTTPCookiePath,  // IMPORTANT!
                            @"testCookies", NSHTTPCookieName,
                            @"1", NSHTTPCookieValue,
                            nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];

NSArray* cookies = [NSArray arrayWithObjects: cookie, nil];

NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];

[request setAllHTTPHeaderFields:headers];

NSHTTPCookie cookieWithProperties example.
// add cookie
    NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
                                req.URL.host, NSHTTPCookieDomain,
                                req.URL.path, NSHTTPCookiePath,
                                @"MLSTORAGE", NSHTTPCookieName,
                                @"1234567890", NSHTTPCookieValue,
                                nil];
    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];
    NSLog(@"\nurl: %@\ncookie: %@", req.URL, cookie);
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    //

End of NSHTTPCookie cookieWithProperties example article.