I am a complete n00b with Obj-C and I'm stuck on this simple thing for hours.
I am using a UIWebView
to load a page which asks for username and password. When I login successfully, my server sends me a cookie with an Id that I want to post to a PHP script in order to store it in db.
When login is successful I get redirected to a new url.
I can read the cookie value and send a POST request to the appropriate script (from my WebView delegate) but doing so, invalidates my login and my page is asking me again for password.
Is this completely wrong approach? Any help on that?
[NSURLConnection connectionWithRequest:request delegate:self];
This is the line of code I run before my session gets invalidated. If I call this from inside the ViewController it works fine, but I need it to run only when I am on a specific url (after login) that's why I have put it in delegate.
Complete (messy) code follows.
NSURL *url = [NSURL URLWithString:@"https://www.example.com/api/register”];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSHTTPCookie *cookie;
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSString *userid;
for (cookie in [cookieJar cookies]) {
if ([cookie.name isEqual: @“cookie_user_id"]) {
userid = cookie.value;
NSLog(@"%@",cookie);
}
}
NSString *getToken = [[NSUserDefaults standardUserDefaults] stringForKey:@"DEVICE_TOKEN"];
NSString *user_id = [NSString stringWithFormat:@"user_id=%@", userid];
NSString *dtk = [NSString stringWithFormat:@"&token=%@",getToken];
NSString *params = [NSString stringWithFormat: @"%@ %@", user_id, dtk];
NSData *requestData = [params dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection connectionWithRequest:request delegate:self];