Showing posts with label NSDate. Show all posts
Showing posts with label NSDate. Show all posts

Thursday, January 10, 2013

Creating a simple typing time checker app in ios

This app is going to deal with the time now. Not a big deal but interesting. The target is to let the user type some text and then displaying how much of time consumed to type the word or sentence.

the design is very simple as this.

All what the user needs to do is to click on start button which confirms whether he is ready for the typing or not. If Yes, then he has to type the shown text in the Text box where the time starts counting. once he/she is done with typing, then have to click on the Done button (actually, when the counting starts, Start button's text changes as Done )

OK, shall we start with the code?













Observe the code of header file first,

#import <UIKit/UIKit.h>

@interface timeCheckerViewController : UIViewController

<UIAlertViewDelegate>                  //since we need alert boxes, we need UIAlertViewDelegate
{
    IBOutlet UITextField *sentence;   //text field to enter the text
    IBOutlet UIButton *startButton;   //button to start the typing process
    IBOutlet UILabel *textToType;   //label which displays the text to type
    
    BOOL gameStarted;                  //Boolean variable to check that the game is started or not
    NSTimeInterval startedTime;      //three variables of NSTimeInterval to calculate time
    NSTimeInterval endTime;
    NSTimeInterval timeTaken;
    
}
@property(nonatomic,retain)UITextField *sentence;
@property(nonatomic,assign)BOOL gameStarted;
@property(nonatomic,retain)UIButton *startButton;
@property(nonatomic,retain)UILabel *textToType;

-(IBAction)start:(id)sender;               //function declaration for start button

-(IBAction)exit:(id)sender;                 //function declaration for exit button
-(IBAction)doneTyping:(id)sender;    //function to send the keyboard away

@end

//--------------------------------------------------------------------------------------------------

Now, check the code of the implementation file below



#import "timeCheckerViewController.h"

@implementation timeCheckerViewController

@synthesize sentence,gameStarted,startButton,textToType;

- (void)dealloc
{
    [sentence release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

//this method runs when the view first loads
- (void)viewDidLoad
{
    [super viewDidLoad];           
    gameStarted=NO;                    //when view loaded first, the game is not started
    startButton.titleLabel.text=@"Start";  //so, the text of the button is Start
    sentence.enabled=NO;             //do not enable the text box to type anything yet    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

//method implemntation of the start/done  button
-(IBAction)start:(id)sender
{
    if(gameStarted==NO)    //if the game is not yet started
    {

//display this alert asking for the user's permission to start the game

        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Typing Game" message:@"Are you ready to start the game?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"YES", nil];
        alert.tag=1;

        [alert show];
    }
    
    //if the game is started

    if(gameStarted==YES) //set the gameStarted as YES (YES is just as TRUE)
    {

//if the user didn't type the gien text exactly, 

        if(sentence.text==@"" || !([[sentence.text lowercaseString] isEqualToString:[textToType.text lowercaseString]]))
        {

//display alert box with error message

            UIAlertView *alert2=[[UIAlertView alloc]initWithTitle:@"Error" message:@"Please type the required text" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            
            [alert2 show];

            sentence.text=@""; //clear the text box
        }
        
//if typed correct
        else
        {
//set the gameStarted variable to NO

            gameStarted=NO;

//set the caption of the Done button as Start

            startButton.titleLabel.text=@"Start";

//get the time when clicked the Done button (end time)
            endTime=[NSDate timeIntervalSinceReferenceDate];    

//get the time diffrrence
       
            timeTaken=endTime-startedTime;

//format a proper message

            NSString *message=[[NSString alloc]initWithFormat:@"You typed the word within %.2f seconds!",timeTaken];

//create an alert view with the message
       
            UIAlertView *alert2=[[UIAlertView alloc]initWithTitle:@"Result" message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
            [alert2 show];
        }
    }
     
}

//this method shows how I want my alert boxes to be
//it is a delegate method implantation of UIAlertViewDelegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag==1)
    {
    
        if(buttonIndex==1)
        {
            if(gameStarted==NO)
            {
                sentence.text=@"";
                gameStarted=YES;
                sentence.enabled=YES;
                startButton.titleLabel.text=@"Done";
                startedTime=[NSDate timeIntervalSinceReferenceDate];   
            }
        }
    }
    
    if(alertView.tag==2)
    {
        if(buttonIndex==1)
        {
            gameStarted=NO;
            exit(0); 
        }
    }
}

//when user clicks on exit button, this function will be called
//it displays an alert box to conform the exit

-(IBAction)exit:(id)sender
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Confirmation" message:@"Are you sure you want to exit from the game?" delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
    alert.tag=2;
    [alert show];
        
}

//if the user is done typing,he can send the on screen keyboard away

-(IBAction)doneTyping:(id)sender
{
    [sender becomeFirstResponder];
}

@end



Now you can build and run your app. I also have made available the project source code for you. 



Some screenshots of the output




Creating a simple ios app with the Date Picker to find what day is it

From the above heading, you might think how stupid it is to make an app to find out the date without checking out the calendar :p It's not what I really mean here. 

I am going to use the UIDatePicker controller to let the user select a preferred date from it and check out what day of the week it is e.g:- if you select your birthday, it should tell you on what day of the week you are born. Interesting, isn't it. It's also simple because it's not even complex as using datasources and delegates as we did discuss in the UIPickerView post.

The design is simple as always, you will understand it from the below diagram

 you have a Date Picker added to your screen. Make sure to select it -->  go to Attributes inspector and select the Mode to Date to let  the user select the day, month and the year only.

You need to have one more button to let the user click after selecting a date.

All the rest are the icing for the app screen :)











now examine the code of the header file below

//  MyDatePickerAppViewController.h

#import <UIKit/UIKit.h>

@interface MyDatePickerAppViewController : UIViewController {
    
    IBOutlet UIDatePicker *dp;        // an object of UIDatePicker to deal with its functions
       
}

@property(nonatomic,retain) UIDatePicker *dp;

-(IBAction) displayDay;                //a method for the button click

@end
//-------------------------------------------------------------------------------------------------------


Next, let's move to the implementation file


//  MyDatePickerAppViewController.m

#import "MyDatePickerAppViewController.h"

@implementation MyDatePickerAppViewController

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@synthesize dp;

-(IBAction) displayDay
{
    NSDate *chosen=dp.date;              //datepicker.date gives the selected date which is an NSDate object
    
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];  //creating an NSDateFormatter object
    
    [formatter setDateFormat:@"EEEE"];                        //we are going to format the date in IEEE standard
    
//find the chosen day's day in the week and get it to a string
    NSString *weekDay=[formatter stringFromDate:chosen]; 
    
//format a message
    NSString *msg=[[NSString alloc] initWithFormat:@"The day is %@",weekDay];
    
//view the message in an alert box
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"What day is it?" message:msg delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
    
    [alert show];
   
    [alert release];
    [msg release];
    [formatter release];    
}

@end

Output of the app is as following

Now you can build and run your app. I also have made available the project source code for you.