Search code examples
iosobjective-cjsonstoryboardrestkit

IOS Login JSON parser with session Id from WebService


Hi I am new to IOS development. I am developing an app that pulls data from a webservice. It has login and logout session and a whole lot of JSON API calls that i intent to implement using RestKit.

Now the issue is my login is working and gets success code 200 but fails to go to the next View Controller Scene because. I don't know how to get the sessionId.

Here is my code and JSON ;

{
  "details": {
    "username": "MY USER NAME",
"password": "MY MD5 CONVERTED PASS" }
}


Expected Returned JSON syntax (Success)

{
  "response": {
"code": 200,
"resp_code": "USER_SESSION_LOGGED_IN", "sid": "as4ads68ds468486essf879g8de9sdg", "session_info": {
"details": {
"firstname" : "MY NAME",
"email_address" : "MY EMAIL", "company_id" : 1,
"user_id" : 1,
"surname" : "MY SURNAME",
"cell_number" : "MY NUMBER",
"username" : "MY USERNAME"
} }
} }
//
//  ViewController.m
//
//  Created by Cockpit Alien on 2014/10/27.
//  Copyright (c) 2014 CockpitAlien. All rights reserved.
//

#import "ViewController.h"
#import <CommonCrypto/CommonDigest.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*+ (NSString*)md5HexDigest:(NSString*)input
{
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, strlen(str), result);
    
    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02x",result[i]];
    }
    return ret;
}*/

- (NSString *) md5:(NSString *) input
{
    const char *cStr = [input UTF8String];
    unsigned char digest[16];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
    
}

- (IBAction)signinClicked:(id)sender {
    NSInteger success = 0;
    NSString *username = self.txtUsername.text;
    NSString *password = self.txtPassword.text;
    NSString *md5Password = [self md5:password];
    
    @try {
        
        if([username isEqualToString:@""] || [password isEqualToString:@""] ) {
            [self alertStatus:@"Please enter Email and Password" :@"Sign in Failed!" :0];
            
        } else {
            NSString *post = [[NSString alloc] initWithFormat:@"username=%@&password=%@",username,md5Password];
            NSLog(@"PostData: %@",post);
            // Create the request
            NSURL *url=[NSURL URLWithString:@"MY JSON HTTP/S URL HERE"];
            
            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
            
            NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
            
            
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            NSLog(@"Request Mutable, %@", request);
            [request setURL:url];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];
            
            //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
            
            NSError *error = [[NSError alloc] init];
            NSHTTPURLResponse *response = nil;
            
            // Create url connetion and fire requests
            NSData *urlData=[NSURLConnection sendSynchronousRequest:request
                                                  returningResponse:&response
                                                              error:&error];
            
            NSLog(@"Response code: %ld", (long)[response statusCode]);
            
            if ([response statusCode] >= 200 && [response statusCode] < 300)
            {
                NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
                NSLog(@"Response ==> %@", responseData);
                
                NSError *error = nil;
                NSDictionary *jsonData = [NSJSONSerialization
                                          JSONObjectWithData:urlData
                                          options:NSJSONReadingMutableContainers
                                          error:&error];
                
                success = [jsonData[@"success"] integerValue];
                NSLog(@"Success: %ld",(long)success);
                
                if(success == 1)
                {
                    NSLog(@"Login SUCCESS");
                } else {
                    
                    NSString *error_msg = (NSString *) jsonData[@"error_message"];
                    [self alertStatus:error_msg :@"Sign in Failed!" :0];
                    NSLog(@"Loging failed");
                }
                
            } else {
                //if (error) NSLog(@"Error: %@", error);
                [self alertStatus:@"Connection Failed" :@"Sign in Failed!" :0];
            }
        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Sign in Failed." :@"Error!" :0];
    }
    if (success) {
        [self performSegueWithIdentifier:@"login_success" sender:self];
    }
}

- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];
    alertView.tag = tag;
    [alertView show];
}
@end


//
//  ViewController.h
//      
//  Created by CockPit on 2014/10/27.
//  Copyright (c) 2014 CockpitAliens. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITextField *txtUsername;
@property (weak, nonatomic) IBOutlet UITextField *txtPassword;
- (IBAction)signinClicked:(id)sender;

@end

Here is my storyboard. I want to be able to login and go to the next view controller. because I am going to also have to logout the sessionId parsing this JSON.

enter image description here


Solution

  • In yoursigninClicked method,

    - (IBAction)signinClicked:(id)sender 
    {
       ....
       ....
    
       if ([response statusCode] >= 200 && [response statusCode] < 300)
       {
       ....
       ....
        if(success == 1)
        {
           NSLog(@"Login SUCCESS");
        }
       ....
       ....
       }
    
       ....
       ....
    }
    

    So you are doing nothing else than printing NSLog. You are checking statusCode is successful or not and in that checking success variable value. In that if condition you should require executable code or method call, which will push application for further execution.