Wednesday, February 6, 2013

Work with ASIHTTPRequest for simple Login in xCode

Hi,  As i have gone through multiple sites to maintain the User Session for multiple calls after login. And User session needs to retain. Then i found ASIHTTPRequest API for Objective C. You can download that from here.

Now the coding part
First You need to declare the delegate in you class (.h) file as follow

#import "ASIHTTPRequest.h"

@interface ConnectionControl : NSObject <ASIHTTPRequestDelegate>

Now for simple login with server, which returns JSON, Follow the code below

-(void) userLoginFromServer:(NSString *)userId andPassword:(NSString *)password
    NSURL *loginURL = [NSURL URLWithString:@""];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:loginURL];
    [request setRequestMethod:@"POST"];
    //Following code will retain username and password for Re-login.
    [request setUsername:userId];
    [request setPassword:password];
    [request setUseKeychainPersistence:YES];
    [request addPostValue:userId forKey:@"username"];
    [request addPostValue:password forKey:@"password"];
    [request setDelegate:self];
    [request setTimeOutSeconds:60];
    [request startSynchronous];
    [request setUseSessionPersistence:YES];

- (void)requestFailed:(ASIHTTPRequest *)request {
    printf("Some Problem");

- (void)requestFinished:(ASIHTTPRequest *)request
    NSData *responseData = [request responseData];
NSString *authJsonString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];
    for(id key in res) {
        id value = [res objectForKey:key];
        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;
        NSLog(@"\nkey: %@", keyAsString);
        NSLog(@"value: %@", valueAsString);
- (void)requestStarted:(ASIHTTPRequest *)request{
    NSLog(@"request started");

No comments:

Post a Comment