views:

1987

answers:

3

Hi there, I'm trying to read cookies using an xcode application im writing for iphone and testing on emulator. However when I run the code below the value stored in mumcookies is 0. Cookies are allowed via iphone settings and I also used mobile safari to navigate to gmail, hotmail and other cookie setting sites to increase cookie count on emulator, but no luck. Your thoughts are much appreciated, really hope Im not doing something real silly :(

NSHTTPCookieStorage *jar = [NSHTTPCookieStorage sharedHTTPCookieStorage]; NSInteger numcookies = [[jar cookies] count];

tony

+3  A: 

Because of sandboxing on the iPhone you don't have access to Safari's cookies. You can only access cookies created within your application - by an UIWebKit for example.

mfazekas
hi mfazekas,Thanks again for your response. The cookies are set via a javascript of a page i load from documents directory of my app into the UIWebView control of my application. Would this ensure that the cookies are stored within my app sandbox?Thanks for your help man.
TonyNeallon
A: 

You might want to check

if ([[NSHTTPCookieStorage sharedHTTPCookieStorage] cookieAcceptPolicy] != NSHTTPCookieAcceptPolicyAlways) {
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];       
}

But apparently NSHTTPCookieStorage does not even hold cookies from the last request in the current application on iOS (rdar://8190706)

valexa
A: 

Here's my utils get/set cookie methods.



+(void)setCookie:(NSString *)key withValue:(NSString *)value {
    NSArray *keys = [NSArray arrayWithObjects:
                     NSHTTPCookieDomain,
                     NSHTTPCookieExpires,
                     NSHTTPCookieName,
                     NSHTTPCookiePath,
                     NSHTTPCookieValue, nil];
    NSArray *objects = [NSArray arrayWithObjects:
                        @"YOURDOMAIN",
                        [NSDate distantFuture],
                        key,
                        @"/",
                        value, nil];    
    NSDictionary *dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:dict];
    NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    [sharedHTTPCookieStorage setCookie:cookie];
}

+(NSString *)getCookie:(NSString *)key {
    NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:[NSURL URLWithString:@"YOURDOMAIN"]];
    NSEnumerator *enumerator = [cookies objectEnumerator];
    NSHTTPCookie *cookie;
    while (cookie = [enumerator nextObject])
    {
        if ([[cookie name] isEqualToString:key]) 
        {
            return [cookie value];
        }
    }
    return nil;
}
Ibrahim Okuyucu