Pages

06 November 2012

ViewController.m

//
//  ViewController.m
//  C9Quickpost
//
//  Created by Mrithula on 10/1/12.
//  Copyright (c) 2012 Mrithula. All rights reserved.
//

#import "ViewController.h"
#import "Globals.h"

#define TAG_LOGIN_VIEW      500
@interface ViewController ()

@end

@implementation ViewController

-(void)removeSplashScreen{
    splashImageView.alpha   =   0.0;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
 // Do any additional setup after loading the view, typically from a nib.
    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(removeSplashScreen) userInfo:nil repeats:NO];
    userDefaults            =   [NSUserDefaults standardUserDefaults];
    appDelegate             =   [[UIApplication sharedApplication] delegate];
    [appDelegate showFooterLabel:NO];
}

-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden      =   TRUE;
    if ([[userDefaults valueForKey:USERDEFAULTS_REMEMBER_LOGIN] intValue]==1) {
        rememberButton.selected =   YES;
        emailTextField.text     =   [userDefaults valueForKey:USERDEFAULTS_LOGIN_USERID];
        passwordTextField.text  =   [userDefaults valueForKey:USERDEFAULTS_LOGIN_PASSWORD];
        [self postLoginRequest];
    }else{
        rememberButton.selected =   NO;
        emailTextField.text     =   @"";
        passwordTextField.text  =   @"";
    }
}

#pragma mark - UITextField Delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField==emailTextField) {
        [passwordTextField becomeFirstResponder];
        [self animateViewIn];
    }else{
        [textField resignFirstResponder];
        [self animateViewOut];
    }
    return YES;
}

-(void)animateViewIn{

    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame =   CGRectMake(self.view.frame.origin.x, -40.0, self.view.frame.size.width, self.view.frame.size.height);
    }];
    
}
-(void)animateViewOut{
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame =   CGRectMake(self.view.frame.origin.x, 0.0, self.view.frame.size.width, self.view.frame.size.height);
    }];
    
}

#pragma mark - NSURLConnection Request and Delegates

-(BOOL)validateEmail:(NSString*)string
{
    NSString *emailRegex                                =   @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9]+(\\.[a-z]{2,4})+";
    NSPredicate *emailTest                              =   [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailRegex];
    return [emailTest evaluateWithObject:string];
}

-(BOOL)validateFields
{
    fieldValidationMessage                  =   @"";
    BOOL valid;
    if ([[emailTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        fieldValidationMessage              =   @"Please enter the Email address";
        valid                               =   NO;
    }
    else if ([[passwordTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        fieldValidationMessage              =   @"Please enter the Password";
        valid                               =   NO;
    }
    else {
        valid                               =   YES;
    }
    return valid;
}


-(void)postLoginRequest{
    
    NSMutableURLRequest *loginRequest    =   [[[NSMutableURLRequest alloc] init] autorelease];
    [loginRequest setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@Authorization/",SERVER_URL]]];
    
    NSString *loginRequestString        =   [NSString stringWithFormat:@"{\"APIKey\":\"%@\",\"UserEmail\":\"%@\",\"Password\":\"%@\"}",API_KEY,emailTextField.text,passwordTextField.text];
    NSData *loginRequestData            =   [NSData dataWithBytes:[loginRequestString UTF8String] length:[loginRequestString length]];

    [loginRequest setHTTPMethod: @"POST" ];
    [loginRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [loginRequest setHTTPBody:loginRequestData];

    loginURLConnection  =   [[NSURLConnection alloc] initWithRequest:loginRequest delegate:self];
    if (loginURLConnection) {
        receivedData    =   [[NSMutableData data] retain];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [appDelegate stopLoading];
 NSError *error              =   nil;
    NSString *responseString    =    [[[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding] autorelease];
    NSData *data                =    [responseString dataUsingEncoding:NSASCIIStringEncoding];
    if (data != nil) {
        NSString *resultString      =   [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
        if (error == nil) {
            appDelegate.auth_token  =   resultString;
            [self performSegueWithIdentifier:@"PushSegueToHome" sender:self];
            
        }else {
            [appDelegate showDismissiveAlertWithMessage:JSON_PARSE_ERROR WithTag:TAG_OTHER_ALERT];
        }
    }else
        [appDelegate showDismissiveAlertWithMessage:@"Could not login. Please try later." WithTag:TAG_OTHER_ALERT];
    
    
    [receivedData release];
    receivedData    =   nil;
    [loginURLConnection release];
    loginURLConnection  =   nil;
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [appDelegate showDismissiveAlertWithMessage:[error localizedDescription] WithTag:TAG_OTHER_ALERT];
    [appDelegate stopLoading];
    [receivedData release];
    receivedData    =   nil;
    [loginURLConnection release];
    loginURLConnection  =   nil;
    
}

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

- (void)dealloc {
    [emailTextField release];
    [passwordTextField release];
    [splashImageView release];
    [super dealloc];
}
- (void)viewDidUnload {
    [emailTextField release];
    emailTextField = nil;
    [passwordTextField release];
    passwordTextField = nil;
    [splashImageView release];
    splashImageView = nil;
    [super viewDidUnload];
}


#pragma mark - IBAction
- (IBAction)loginButtonClicked:(id)sender {
    if ([self validateFields]) {
        if ([self validateEmail:emailTextField.text]) {
            [appDelegate startLoading];
            if (rememberButton.selected) {
                [userDefaults setObject:emailTextField.text forKey:USERDEFAULTS_LOGIN_USERID];
                [userDefaults setObject:passwordTextField.text forKey:USERDEFAULTS_LOGIN_PASSWORD];
                [userDefaults synchronize];
            }
            [self postLoginRequest];
        }else{
            [appDelegate showDismissiveAlertWithMessage:@"Invalid E-mail address" WithTag:TAG_OTHER_ALERT];
        }
        
    }else{
        [appDelegate showDismissiveAlertWithMessage:fieldValidationMessage WithTag:TAG_OTHER_ALERT];
    }
}

- (IBAction)rememberButtonClicked:(id)sender {
   rememberButton       =   sender;

    if (rememberButton.selected) {
        rememberButton.selected =   NO;
        [userDefaults setObject:@"0" forKey:USERDEFAULTS_REMEMBER_LOGIN];
        [userDefaults removeObjectForKey:USERDEFAULTS_LOGIN_USERID];
        [userDefaults removeObjectForKey:USERDEFAULTS_LOGIN_PASSWORD];
    }else{
        rememberButton.selected =   YES;
        [userDefaults setObject:@"1" forKey:USERDEFAULTS_REMEMBER_LOGIN];
    }

    [userDefaults synchronize];
}
@end

0 comments: