문제

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.

도움이 되었습니까?

해결책

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);
  }];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top