chaithu
chaithu

Reputation: 519

HTTP session cookies in iOS

I'm a novice iOS developer. I have an application which requires login and it has functions which make HTTP requests through out the app. As per my understanding, When a login happens server sends the app a unique session cookie which we need to use with further HTTP requests in the same session. My method which makes HTTP request is as below. All the requests in my application use this same method.

+ (NSData*)makeHTTPPostRequestToURL:(NSURL *)url withPostString:(NSString *)postString{

    if (!postString)
    {
        postString = [NSString stringWithFormat:@""];
    }

    NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:url];

    NSString *authStr = [NSString stringWithFormat:@"genuser:genuser"];
    NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
    NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
    [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [urlRequest setValue:[NSString stringWithFormat:@"%lu", (unsigned long)postString.length] forHTTPHeaderField:@"Content-Length"];
    postString =[self specialencoding:NSUTF8StringEncoding :postString ];

    NSLog(@"Request log is %@", postString);

    [urlRequest setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    NSLog(@"POST:ESCAPED:%@",postString);
    NSHTTPURLResponse* urlResponse = nil;
    NSError* error = nil;

    NSData* responseData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&urlResponse error:&error];

    return responseData;
}   

As you can see I'm not using the cookie when I'm making the request in the same session. All the requests work fine. My doubt is how is the request being served in the same session if don't send the cookie with it. Does iOS save the last received cookie for each app and append it with the further requests the app makes. Any insights ?

Upvotes: 0

Views: 1872

Answers (1)

thatidiotguy
thatidiotguy

Reputation: 8991

So what is happening is that cookies sent back are stored in the NSHTTPCookieStorage object. Whenever requests are sent back to a URL matching the cookies domain and path, the cookie is sent along with the request automatically.

To check what cookies are there for a particular domain:

let url = NSURL(string: "https://yourcookiedomain.com")!;
let cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage();
let cookies = cookieStorage.cookiesForURL(url) as Array<NSHTTPCookie>;

var cookie: NSHTTPCookie? = nil;
for c in cookies {
    if (c.name == "cookie_name") {
       cookie = c;
       break;
    }
}

Upvotes: 2

Related Questions