09 August, 2010

Implementing Login authentication

In my example I have two text fields like below:
mUserNameTextField : Where user can enter his user name.
mPassWordTextField : Where user can enter his password.


Sending request to server:
First we need to create NSURLRequest, and use NSURLConnection to talk to your server.
NSString *urlStr = [NSString stringWithFormat:@"?username=%@&password=%@", mUserNameTextField.text, mPassWordTextField.text];
NSURL *url = [[NSURL alloc] initWithString:urlStr]; 
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
NSHTTPURLResponse* response = nil; 
NSError* error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];


Authentication response can be in two forms:
1) get the response in resposeData variable (returned from sendSynchronousRequest).
2) Write response data to some XML file in your server then read that response from your server.
In this example I am using second method.


Reading data from server:

NSString *urlStr = [NSString stringWithFormat:@"/uservalidation.xml"];
NSURL *url = [[NSURL alloc] initWithString:urlStr]; 
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
NSHTTPURLResponse* response = nil; 
NSError* error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];


After reading the data from server you can parse ti and then do necessary things:
NSXMLParser* results = [[NSXMLParser alloc] initWithData:responseData];
[results setDelegate:self];
[results parse];

No comments:

Post a Comment