Question

Firstly, the app would open a UIWebView to a login page on my website, upon successful log in, the webview will be closed. There's a url I need to request which would return a very small json data. If I were to launch this url with a webview, the correct data is returned, thus assuming the log in session is still alive (if its not, it would be redirected to the login page again)

Instead of a webview, I need the data returned in another view, thus I would need to access it using NSURLRequest instead. After crawling stackoverflow for an evening, the following is what I have:

NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:
                          [cookieJar cookies]];
[request setAllHTTPHeaderFields:headers];

NSError * e;
NSData  *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];

upon inspecting the returned data, which consist of the login page source instead of the expected json data, I can conclude that the cookies were not sent, need advice.

EDIT: I did an output of [request allHTTPHeaderField] and it showed that all available cookies inside NSHTTPCookieStorage had been attached to the request. So... Am really lost how I should proceed.

Was it helpful?

Solution

You don't need to set cookies explicitly. NSURLConnection does this automatically for you.

Did you try printing out the cookies after your webview is closes?

  [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

    NSLog(@"%@", obj);
  }];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top