Showing posts with label XCode. Show all posts
Showing posts with label XCode. Show all posts

Thursday, November 7, 2013

Parsing XML files in iOS using XPath

Hi all. After a long break I have decided to add another post to my blogger about another interesting post and a technique that found really challenging to me while working on a certain project recently. OK, this time I'm going to explain how I solved a bit of a tough task of parsing an XML file from an iOS Application easily. Keep one thing in your mind that I will not be using 100% of my own code in this post but I will be instructing you to download few header and implementation files to your project in order to perform this task. Also note that you also require a well formatted valid XML file to test your app and ensure that the parsing of XML task is done as you expected.

By the way, let's quickly go through some very simple questions before starting with the code. Try to understand the following and make sure you know the background of what I'm going to perform here.

XML... what's it about?

XML stands for Extensible Markup Language and it is a markup language (everything is marked as a tag) that defines a set of rules for encoding documents in a format that both human-readable and machine-readable. 

Why XML is so popular?

I don't think that anyone in the field of Information Technology will ever tell that they have never heard the word XML since it is so popular because the design goals of XML highlight simplicity, generality and usability over the Internet. XML files are simply text files and no mater of the platform or technology we are using XML can be understood by all of them.

Well Formed Vs Valid XML Documents

A "Well Formed" XML Document has correct XML syntax. For an example, 
  • XML documents must have a root element
  • XML elements have a closing tag
  • XML tags are case sensitive
  • XML elements must be properly nested
  • XML attribute values must be quoted

A "Valid" XML document is a "Well Formed" XML document which is also confirms to the rules of Document Type Definition (DTD)

How to Validate your XML file?

Let's say that you have an XML file with you and you want to validate it to check for it's syntax. you have a number of tools to do this but let's make it simple. Follow the below links to find out how this task can be easily done through online tools within few seconds. All what you have to do is to simply copy paste the content of your XML file or browse your XML file in the given URL and use the validator to check your file.


OK, now let's move to the most interesting part of our post today. As I told you earlier, we need to have a valid and well formed XML file and it is going to be the below shown file.


File content is as below,

<services>
<service name="Service1" url="/utilities/service1.xml">
<type>GET</type>
<parameter-mapping enumvalue="ID">ID</parameter-mapping>
<parameter-mapping enumvalue="NAMEOFDEVICE">DeviceName</parameter-mapping>
<parameter-mapping enumvalue="SERIALOFDEVICE">Serial</parameter-mapping>
<parameter-mapping enumvalue="IPADDRESS">IP_Address</parameter-mapping>
<parameter-mapping enumvalue="STATUS">status</parameter-mapping>
</service>
<service name="Service2" url="/utilities/service2.xml">
<type>POST</type>
<parameter-mapping enumvalue="DEVICEUNIQUEID">UniqueId</parameter-mapping>
<parameter-mapping enumvalue="PASSWORD">password</parameter-mapping>
<parameter-mapping enumvalue="PAIREDDEVICEID">PairedTabletID</parameter-mapping>
<parameter-mapping enumvalue="STATUS">status</parameter-mapping>
</service>
</services>

I have added this xml file to my project resources in the sample XCode project that I've created by just dragging and dropping it to the project file hierarchy as below.


























OK, Now we have simply added the required XML file to our XCode project. Now it's time to get the content of the XML file and start parsing it using our app.

By the way, Do you know how to read an embedded file from an XCode project in Objective-C?


It's simple. Just a matter of adding few lines of code to get the file content to an NSString. Refer the code below.


NSData *configXmlData;
/*
*Function reads the embedded SampleXMLFile.xml file and saves to an instance variable call configXmlData of type NSData
*@return : no data returned
*/

-(void)setConfigurationFile
{
    //reading the resources from the mainBundle of where it search for a file named SampleXMLFile with file extension of xml
  NSString *configXmlFilePath=[[NSBundle mainBundle] pathForResource:@"SampleXMLFile" ofType:@"xml"];

  @try
  {
   //if the file exist, then get the contents of the file to the configXmlData variable 
   if([[NSFileManager defaultManager]fileExistsAtPath:configXmlFilePath])
   {
    configXmlData=[NSData dataWithContentsOfFile:configXmlFilePath];
   }

  }

  //if incase of an error occurs (file doesn't exist or user has no privilege to access it etc ), then print this error message in NSLog
  @catch (NSException *exception)
  {
   NSLog(@"Exception Occurred in reading setConfigurationFile: %@ ",exception);
  }
}


Now Let's turn on the XPath related work now. Keep in mind that I am going to use some files for this purpose that are available in GitHub in the Hppl Project. Use the below shown link to access the Hppl project.

Access Hppl Project From Here

download the project above and add these files to your project.
  • TFHppl.h
  • TFHppl.m
  • TFHpplElement.h
  • TFHpplElement.m
  • XPathQuery.h
  • XPathQuery.m
remember that you need to add reference to these header files from your Xcode project.

What Am I going to do now...

Ok, let's come to the main target of this post. Here's what I am going to do. I hope you have noticed the structure of the above shown XML file. All what I m going to do is to extract the data of that file as I wanted. Let's say I don't need the entire file content always but a part of it is sufficient for me to perform a task as shown below.

When I pass a string called 'Service1' then the app should display the output as below.

url=/utilities/service1.xml
type=GET
ID=ID
NAMEOFDEVICE=DeviceName
SERIALOFDEVICE=Serial
IPADDRESS=IP_Address
STATUS=status

when I pass s string 'Service2' then the app should display the output as below.

url=/utilities/service2.xml
type=POST
DEVICEUNIQUEID=UniqueId
PASSWORD=password
PAIREDDEVICEID=PairedTabletID
STATUS=status

My plan is to write a simple XML parser function to read tags, attributes, elements and values of the XML file accordingly with the help of the methods included in Hppl Project that we have just added to the project. It's really easy and all what you have to pay a little more attention is for the XPath query that you are suppose to write to extract the matching XML elements.
For simplicity, I'll explain you the methods one by one and then you can download the sample app and monitor how things are handled as a whole.

Note that MetaConfigurationHandler is the name of the class that I have and you need to add two more reference for it as below.

#import "TFHpple.h"
#import "Discovery.h"
 
 
/*
*Function creates an NSDictionary containing all the data required for a specific http connection as key value pairs
*@return : an NSDictionary containing the required key value pairs
*/

-(NSDictionary *)generateConfigurationDictionary:(NSString *)request
{
//calls the above mentioned function to read the embedded xml

//file contents to the instance variable configXmlData
  [self setConfigurationFile];

//holds each value for each key of the dictionary
  NSString *valueForKey=nil;

//holds each key of the dictionary
  NSString *key=nil;

//holds the name of the tag
  NSString *tagName=nil;

//holds the xPath query (what matching string we are searching for)
  NSString *xPathQuery=nil;

//holds all the elements of the Services tag
  NSArray *configurationServiceElements=[NSMutableArray array];

//this will be returned as an output containing the aforementioned
//NSMutableDictionary with keys and values respectively
  NSMutableDictionary *configurationDictionary =[NSMutableDictionary dictionary];

@try
{
//xpath query string to search for the children of service tag

//where the service's name= request (here, request is a string
//as Service1 or Service2 that is passed to this function as
//a parameter
  xPathQuery=[NSString stringWithFormat:@"/services/service[@name='%@']",request];

//passing the xPath query, retrieving all the tags that are

//matching with the above xPath query
//configurationServiceElements array will hold elements like url,
//type,ID,NAMEOFDEVICE,SERIALOFDEVICE,IPADDRESS and STATUS

//when request=Service1

  configurationServiceElements=[self getConfigurationElementArray:xPathQuery];

 //valueForKey is going to hold /utilities/service1.xml

//(when request=Service1)
  valueForKey=[[configurationServiceElements objectAtIndex:0] objectForKey:@"url"];

//add value=/utilities/service1.xml where key=url

//(when request=Service1) which
//means configurationDictionary will hold one entry with a key-value pair
  [configurationDictionary setObject:valueForKey forKey:@"url"];

//clear the xPathQuery
  xPathQuery=nil;

//xpath query string to search for the value under the tag named as type and
//which is a sub element od Services/service where service name is equal to
//request
  xPathQuery=[NSString stringWithFormat:@"/services/service[@name='%@']/type",request];

//pass the query to get the value
  configurationServiceElements=[self getConfigurationElementArray:xPathQuery];

//how to get the value of the tag which is type
  valueForKey=[[[configurationServiceElements objectAtIndex:0] firstChild] content];

//add this key value pair to the dictionary,  configurationDictionary
  [configurationDictionary setObject:valueForKey forKey:@"type"];


/*Now, I'm trying to get all the tags under /services/service that are named as
parameter-mapping, then get(element) each of its attribute values and element values to form the key-value pairs for the dictionary as
ID: ID
NAMEOFDEVICE=DeviceName
SERIALOFDEVICE:Serial etc
*/


//first the xPath query search for parameter-mapping elements
//under services/service
  xPathQuery=[NSString stringWithFormat:@"/services/service[@name='%@']/parameter-mapping", request];

//get all those elements that matches the xpath query above to an array
configurationServiceElements=[self getConfigurationElementArray: xPathQuery];
 

//now for each element in the configurationServiceElements array...
  for (TFHppleElement *element in configurationServiceElements)
  {

         //get the name of the tag and assign to tagName variable
     tagName=element.tagName;
       

     //check if that tagName is equal to parameter-mapping
     if[tagName isEqualToString:@"parameter-mapping"])

     //if true, assign it to key          
      key=element.tagName;

     //get the attribute of parameter-mapping which is enumvalue and
     //make it a key
     key=[element objectForKey:@"enumvalue"];


          //get the value of the attribute named key (which means enumvalue)and
     //assign it to valueForKey
     valueForKey=[[element firstChild]content];
     

     //now add those key-value pair to the configurationDictionary as
     //another entry 
     [configurationDictionary setObject:valueForKey forKey:key];          
  }
}

  //if incase an exception occurs then handle it by printing the exception
  //in NSLog
  @catch (NSException *exception)
  {
    NSLog(@"Exception Occurred in generateConfigurationDictionary:%@ ",exception);  
  }

 //finally, return the configurationDictionary NDmutableDictionary
  @finally
  {
    return configurationDictionary;
  }

}
 

/*
*Function executes an xpath query and returns the matching nodes as an NSArray to the callee
*@xPathQuery : xpath query as a string should be passed
*@return : an NSArray containing the matching elements will be returned
*/

-(NSArray *)getConfigurationElementArray:(NSString *)xPathQuery
{
  NSArray *servicesNodes;
  TFHpple *servicesParser = [TFHpple hppleWithXMLData:configXmlData];
  NSString *servicesXpathQueryString = xPathQuery;               
  servicesNodes = [servicesParser searchWithXPathQuery:servicesXpathQueryString];
  return servicesNodes;
}


Now, the most required or I would rather say most difficult part of our XML parsing is done. All what you have to do is to make relevant function calls passing proper parameters to get the output as you want.


for an example, I can call the parser functions as shown below. Assume that I am going to call these functions from another class

MetaConfigurationHandler *meta=[[MetaConfigurationHandler alloc]init];

NSDictionary  *configDic=[NSDictionary  dictionary];

*configDic=[meta generateConfigurationDictionary:@"Service1"];


Now you can simply print the configDic contents in NSLog or as you preferred. 

Hope this post was interesting to you guys  :)

Further reading :

http://www.w3schools.com/xml/default.asp
http://www.raywenderlich.com/14172/how-to-parse-html-on-ios

Friday, January 11, 2013

Creating a simple student's information system in ios using sqlite

I have explained little little applications in ios throughout some previous posts under IOS page in my blog. Now i thought t's time to refresh the beginners knowledge in ios where they can apply all what they've learned so far to make a little database system.

The database that we are going to use in ios apps is sqlite. If you are a beginner, then you may question me,

Why SQLite?

SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. SQLite is the most widely deployedSQL database engine in the world. Due to its small size, SQLite is well suited to embedded systems and mobile apps like ios.

if you are using sqlite database in your ios app, you need to add a framework to the project.  follow the steps below to do so

Adding sqlite framwork to an ios project

  1. select your project


2. expand the Link Binary With Libraries menu


3. select libsqlite3.dylib and click Add
 3. you will see that it is added to your project root folder. drag and drop it in the Frameworks folder for better organization


Now, let's focus on the designs. Actually I have made a collection of views to make the app easy to understand.

Below are the screens I have




Main screen ( StudentsDBSystemViewController.xib)

Basically, it has a segmented control which provides access to all other screens. The codes for this are already discussed in the previous posts. You can download the code and refer for clarification.

















Registration Screen (RegistrationView.xib)

It has few labels and text boxes to enter students basic details. When it comes for a date as date of birth, users may make mistakes in entering it to the system. So that the best is to use a Date Picker control for this and let then select the day,month and the year. Once the date is selected from the picker, user can click on Get  button to get the date to copied to the text box below

if the required data is provided, user can click Add  to insert a record of a new student to the system. can click Update button to update any details or click Home to go back to the main screen.










Search and Update screens (UpdateSearchDelete.xib and Student.xib)

once you select the search button in the main screen, all what you get is a screen which holds a UITableViewController displaying all the available Students IDs in the database. you can select one of it and it redirects you to another screen which displays that particular student's complete details . All except the student ID is changeable  So, if the user wants to make any change in the existing data, he/she can do them and click on Update  button to save in the database. 
Or if the user wishes to remove the student permanently from the system database, it can be done by clicking on Remove button. 
Notice that even this button can be clicked by mistakenly which too lets the students records to be deleted permanently from the database. We should avoid this with a confirmation dialog box.





















About Screen (About.xib)

It's just a matter of adding a label and  a text view and display a text that is done via this screen.


I think without explain the source code here, It's better if you can examine the source code and understand it. 
I also made available the project source code for you.

Click to Download






Creating a Twitter application in ios

Twitter is an online social networking service and microblogging service that enables its users to send and read text-based messages of up to 140 characters, known as "tweets". It's quite popular nowadays since people likes to update the world about what they are currently doing, what they found interesting today, how they feel the day and so on as little tweets.

Why I am telling these info to you is that now we are going to discuss an ios app which you can install in your iphone to tweet easily without visiting twitter site. The types of tweets that we are going to use is limited but the way we do that is interesting. 

The following image shows how the design should be done. 

what actually happens here is, we are going to have a Picker view with two columns( user can select two items from each column), that helps to form your tweet saying how are you today and how do you feel about that. So, all what the user has to do is to select them and click on Tweet it! button to post a tweet in his/her twitter page. Simple, but interesting.

once you are done with the design, don't forget to set the UIPickerView data source and delegate to the picker view we have here.
OK, I'll jump to the code now. 











//  InstaTwitViewController.h

#import <UIKit/UIKit.h>

@interface InstaTwitViewController : UIViewController

//we are going to use the UIPickerView datasource and delegate methods

<UIPickerViewDelegate,UIPickerViewDataSource>  
{
    IBOutlet UIPickerView *tweetPicker;  //two objects to hold the controls
    IBOutlet UITextView *notesField;       
    
    NSArray *activities;     //two arrays to hold the two parts of the tweet
    NSArray *feelings;
}
@property(nonatomic,retain)UIPickerView *tweetPicker;
@property(nonatomic,retain)UITextView *notesField;

-(IBAction)sendButtonTapped:(id)sender; //method to sent the tweet
-(IBAction)textFieldDoneEditing:(id)sender;

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

Now, we'll see how these can be implemented.


#import "InstaTwitViewController.h"

@implementation InstaTwitViewController

@synthesize tweetPicker,notesField;

- (void)dealloc
{
    [activities release];
    [feelings release];
    [tweetPicker release];
    [notesField release];
    [super dealloc];
}

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

#pragma mark - View lifecycle

//this method will be invoked when the app loads for the first time
//we are going to make two NSArrys named activities and feelings and store a collection of related strings
- (void)viewDidLoad
{
activities=[[NSArray alloc]initWithObjects:@"sleeping",@"eating",@"working",@"thinking",@"crying",@"begging",@"leaving",@"shopping",@"hello worlding", nil];

feelings=[[NSArray alloc]initWithObjects:@"awsome",@"sad",@"happy",@"ambivalent",@"nauseous",@"psyched",@"confused",@"hopeful",@"anxious", nil];

    [super viewDidLoad];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    activities=nil;
    feelings=nil;
    tweetPicker=nil;
    notesField=nil;  
}

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

//-------------------UIPickerView datasouce methods-----------------------------------------------------
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

// returns the # of rows in each component..
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{

 //we need the number of elements in the activities array to be the number of rows in the first column 
//(here you call it component)

    if(component==0)         
        return [activities count];

//we need the number of elements in the feelings array to be the number of rows in the first column 
    if(component==1)
        return [feelings count];  
}

//-------------------UIPickerView delegate methods-----------------------------------------------------
//to set values for each cell of the UIPickerView
//we use a switch block here to see to which column we are addressing at the moment
//if it is component 0 then have to pass the rowth element of the activities array 
//if component 1, do the same with the feelings array

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component) 
    {
        case 0:
            return [activities objectAtIndex:row];
            break;
            
        case 1:
            return [feelings objectAtIndex:row];
            break;
            
        default:
            break;
    }
    return nil;
}

//this method will be called if the user selects items from each of the columns of the picker view
-(IBAction)sendButtonTapped:(id)sender
{

//get each comlumn's selction to variables

    NSString *selectedAcivity=[activities objectAtIndex:[tweetPicker selectedRowInComponent:0]];
    NSString *selectedFeeling=[feelings objectAtIndex:[tweetPicker selectedRowInComponent:1]];
    
//format the tweet

 NSString *message=[[NSString alloc]initWithFormat:@"%@ I'm %@ and feeling %@ about it.",notesField.text ? notesField.text :@"",selectedAcivity,selectedFeeling];
  
//display the   
    NSLog(message);
    
  //TWITTER API starts here to pass our message to twitter
  //TWITTER BLACK MAGIC    
  
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:yourTwitterUserName.com:yourTwitterPassword@twitter.comstatuses/update.xml"]
                                                            cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                        timeoutInterval:60.0];

    [theRequest setHTTPMethod:@"POST"];

    [theRequest setHTTPBody:[[NSString stringWithFormat:@"status=%@",
                              message] dataUsingEncoding:NSASCIIStringEncoding]];

    NSURLResponse* response;
    NSError* error;
    NSData* result = [NSURLConnection sendSynchronousRequest:theRequest
                                           returningResponse:&response error:&error];

    NSLog(@"%@", [[[NSString alloc] initWithData:result
                                        encoding:NSASCIIStringEncoding] autorelease]);

    // END TWITTER BLACK MAGIC    
    
}

//this method will send the onscreen key board way when clicked on return button in it

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

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



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


you can observe the output below. You have to keep one more thing here, if you are using the simulator to test this app, you will see the processing javascripts in the log only. if you test this in a device, your tweets will be posted in your twitter wall




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.