Pages

Labels

Tuesday, May 29, 2012

Adding validation to UITextfields

Create the Function Named validate Input &Defined it as Given Below



-(BOOL)validateInput{
    
    BOOL retvalue=YES;
    NSString *throwmessage;
    
    if ([LocationName.text isEqualToString:@""] || LocationName.text==nil
        
    {
        throwmessage=@"Please Enter Location Name";
        retvalue=NO;
    }
    
    else if ([City.text isEqualToString:@""] || City.text==nil
        
    {
        throwmessage=@"Please Enter City ";
        retvalue=NO;
    }
    else if ([Area.text isEqualToString:@""] || Area.text==nil
        
    {
        throwmessage=@"Please Enter Area ";
        retvalue=NO;
    }
    
    else if ([State.text isEqualToString:@""] || State.text==nil
        
    {
        throwmessage=@"Please Enter State";
        retvalue=NO;
    }
    
    else if ([Country.text isEqualToString:@""] || Country.text==nil
        
    {
        throwmessage=@"Please Enter Contact Number ";
        retvalue=NO;
    }
      
    if (retvalue==NO
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:throwmessage delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];       
    }
    return  retvalue;
    
}   






Check 0r call this function When Required

Such AS

-(IBAction)Save{

if([self validateinput]){


}
else{



}

Thursday, May 24, 2012

A Quick Guide For NSUserDefaults

Here is a quick reference for some of the things you can do with NSUserDefaults
Saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:@"floatKey"];

Monday, May 21, 2012

Adding textField in UIAlertView

UIAlertView* myAlert = [[UIAlertView alloc] initWithTitle:@"Enter Name" message:@"Enter Name
" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];

[myAlert addTextFieldWithValue:@"" label:@"name-age"];
myTextField = [myAlert textFieldAtIndex:0];
myTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
myTextField.keyboardType = UIKeyboardTypeAlphabet;
myTextField.keyboardAppearance = UIKeyboardAppearanceAlert;
myTextField.autocapitalizationType  = UITextAutocapitalizationTypeWords;
myTextField.autocorrectionType = UITextAutocapitalizationTypeNone;
myTextField.textAlignment = UITextAlignmentCenter;

[myAlert show];
[myAlert release];

Thursday, May 17, 2012

How to Change the AlertView backround

       


       UIImage *theImage = [UIImage imageNamed:@"alert.png"];    
       theImage = [theImage stretchableImageWithLeftCapWidth:16 topCapHeight:16];
        CGSize theSize = [deletealert frame].size;
        
        UIGraphicsBeginImageContext(theSize);    
        [theImage drawInRect:CGRectMake(0, 0, theSize.width, theSize.height)];    
        theImage = UIGraphicsGetImageFromCurrentImageContext();    
        UIGraphicsEndImageContext();
        
        [[deletealert layer] setContents:[theImage CGImage]];
        [deletealert release];
        
        

Email validation in iphone

- (BOOL) isValidEmail:(NSString *) email {
errorMessage = [NSMutableString stringWithString: @""];
BOOL validEmail = YES;
NSString *emailRegex = @"[a-zA-Z0-9.\\-_]{2,32}@[a-zA-Z0-9.\\-_]{2,32}\[A-Za-z]{2,4}";
NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
validEmail = [regExPredicate evaluateWithObject:email];
if (!validEmail) {
errorMessage = [NSMutableString stringWithString:@"Invalid Email"];
        validEmail = NO;
        NSLog(@"Invalid Email");
}
if ([email length] > 30) {
errorMessage = [NSMutableString stringWithString:@"Very Long Email"];
validEmail = NO;
        NSLog(@"Very Long Email");
}
if ([email length] == ZERO_LENGTH) {
errorMessage = [NSMutableString stringWithString:@"Please type valid email id"];
validEmail = NO;
        NSLog(@"Please type valid email id");
}
return validEmail;
}

Monday, May 14, 2012

JSON web Services in Iphone


JSON is nothing but java web service. We will make rest call to invoke the JSON web services. To parse the data, we should import JSON classes in our application. We can parse the result in connectionDidFinishLoading method. We will see one small example to analyze the parsing function using JSON parser.

9.2  JSON Parsing with Example

         We have to start with Xcode and create a view based application. Now, we have to add JSON classes in to our application, for that right click on the application name and choose Add Files. After adding the Files application will be look as follows,





         You can see  JSON classes in the left pane of Xcode window. Now come back to the header section and import JSON.h file in it.  We have to define UILabel to print the result and NSMutableData to get the result from service. To invoke the action, we have to declare one action in the header section, finally header file will be look as follows,








         Now come to implementation section and define the action.We have to implement the connection for result data in the connection delegates. The code will look as follows,



        
         In connection finish loading file we have to parse data. Here, data will be get as dictionary format, so we have to get desire result by using the keys as follows,



        
         We will get the response data and we have to convert that encoded data as string by using NSUTF8 encoding method. Then we have to store the parse result in one array, for that purpose we  are using latest loans array by getting the JSON value for string.
         Connect the actions and outlets in the xib and build and run the application. We will get the output as follows,









Sunday, May 13, 2012

XML web Services in Iphone


         Web services are used to connect the database server to store and retrieve data. Web services are the bridge between view part and database. In iPhone, we have to handle the web services to parse the data. In the case of xml web service, Xcode itself provide an xml parser to parse the data from web services.
         To use the parser delegates, we have to add NSXmlParserDelegate in the header section. First we have to send a soap request to get the XmlData. After getting the XmlData, we have to parse it locally.

8.2  Send Soap Request and get XmlData



          We shall see an example for web service implementation. Starts with Xcode and create one view based application. Come to header file, add xmlParserDelegate , action and Declare  object for NSMutableData in the header section.

         After the declarations, header file will be like as follows,




        
         Come to implementation section and define the action invokeWebService. In invoke web service action, we have to implement the soap call. In this application, we are using one free web service to get the name of all countries in the world.

         We will get the web data as a bulk of countries and we have to parse that web data and store the list of countries in an array. Web service  soap message is available in following link,         

         Now the we shall see the implementation coding for invokeWebService action,












         We should set soap request as a string namely “SoapMessage” and set up an url with the http link. After that, we have to set URLRequest by adding header , content length , etc.

         After send the soap request, we have to initialize and set up the connection to get the web data.


 








        
         In connection finish loading function, we shall print the web data result to see whether the process is done properly . Web data will be of encoding type, first we shall convert that to a string by  applying UTF8Encoding scheme. The  result will be printed as follows,


        
8.3  Parsing and Store the XML data using XMLParser delegates.

         Now, we shall see the xml parsing process for the xml data which get through previous process. In the connection finish loading method, initiate the xmlParsing with xml data by adding following codings as follows,

    if (xmlParser)
    {
        [xmlParser release];
    }
    xmlParser = [[NSXMLParser alloc] initWithData: webdata];
    [xmlParser setDelegate:self];
    [xmlParser setShouldResolveExternalEntities:YES];
    [xmlParser parse];

         The above coding will initiate the parsing delegate functions , We have to write codes inside the delegate functions to parse and store the data in array. Following are the list of available XMLParser delegate functions,




          We can use the delegate functions as per our requirements, mainly we have to use three delegate functions to parse the data as follows,





        
         We have to declare a string called “parselemntname”  and a mutable array called
countryList in the header section and initialize the array in viewDidLoad function. Parse Element name  string will contains the current element name and by using the element name, we have to append data in the array in foundCharacter method.

         To print the array, use NSLog in didEndElement method. Finally we will get the array as follows,




         We can show the results using a table view or picker in iPhone.





8.4  UIActivityIndicator in iPhone

         Dealing with web service is a complex process. Some times it may took times to load the data from the server. To indicate that the process is still running, we have to use activity indicator view in our application.

         Add UIActivityIndicatorView object in the header section. In the implementation section, add two lines coding in invoke function as follows,




         here, av means activity indicator view object. In the connection finish loading method stop the animating and hide the activity view. Finally connect the outlets and actions , build and run the application, we will get the output as follows,





        





         8.5 Displaying data using TableView

         We get country list in array, now we have to display data using table view. For that purpose we have to Declare UITableView datasource and delegate in the header file. The header file will be look as follows,





         Now come to implementation section. In connection finish loading function , after the parsing code, reload the table using [tv reloadData] and set data source as follows,




         Now connect the actions and outlets in the xib file. Also connect datasource and delegate function of table view in to file's owner. We will get the output as follows,













Sunday, May 6, 2012

SQLite Database Operations In iPhone



            7.1 Introduction

            To store small amount of data, array can be used. But in the case of large amount of data, we have to switch to some other option. Xcode allow the user to use sqlite3 data base for storage purpose. Sqlite allow the developer to create, store, delete, update a database table and provide a large amount of storage to store different types of data.

         In this session, we will see create a data base, create table, insert data in the table, delete data and finally update data in the table.


         7.2 Create a database and table in iPhone

         Now, we shall see how to create a database and table in iPhone development. First you have to create a Xcode project namely SqlDB ( you can give your own name), and in the framework section on the right pane, right click and add new frame work for sqlite called libsqlite3.0.dylib.
In the SqlDBViewController.h file, import the sqlite3 database header file.

          



         ViewUser.h is another one view controller file which is used to display the detail data for particular user. Table view is used to display the stored data from data base to iPhone. TextFields are used to get the data to store. We can directly get and set data from data base to table, for that we have to use set of arrays, so declare 3 array objects in the header section.

         Functions which are declare in the header section is used to create, open and store data in the database table.

         Now, we shall see the implementation coding for create a database and table in iPhone.










         By using the method  (NSString*)filePath, we will create one database.sql file in application's local folder. OpenDB is the function which is used to open a database. Create table function is used to create a table in database. We can define the create table query as per the requirement. Here, the table is created with three fields, namely UserId, User_Name and Password. User_Id is set as auto increment and we will get user name and password  as input.

         In create table function, first we have to define the create table query and save that in a string.
sqlite_exec query is used to execute the database queries. We have to pass   parameters in sqlite_exec such as database object, sql query and a character which indicate the error . If the execution process is succeeded, the table was created successfully otherwise close the database and show the error message.


7.3  Insert data in the table

         After creating a database table, we have to insert data in to data base table. For that purpose,
we have to write code as follows in the implementation section,



        

        
         Above method will insert the data in to the database. Here, we are inserting two fields namely user_name and password. So that the insert data function is defined using two fields .Here, first we have to define a query to insert the data in the table and pass that query in the function called sqlite3_prepare_v2. This will check whether the appropriate data are passed as input parameters , if the query was successful one, then bind the text in the database table by using the function sqlite3_bind_text. If   sqlite3_prepare_v2 function fails, throw an error message and close the database.

         To call insert data method, we have to define another one IBAction as follows,






         In the above function, first step is to open the database by calling openDB function using [self openDB]  and also call createTable function to create a table. Finally call insertRecord  function and close the database.

7.4 Select records from database table

         After insert the data in table, next step is to get and display the data in a table. Here, we have to write codes to get data from database as well as to store that in  arrays. Similar to previous process, first we have to write query to get the set of rows from table and prepare the query for validation. Finally, if the process was succeeded, then append each data from the table to array.

         Here, we are going to get three fields namely user_Id, user_name, password in three separate arrays. By using the name array we are reloading the table data.

         The implementation section coding for select records from the database table is as follows,

        




         Table view datasource coding will be as follow,





         7.5 Update and delete record from table
        
         Now we have to display each user data in detail manner. For that purpose, we have to use our second view controller file namely  “ViewUser”.  In the header section, import and declare object for sqlite3 database. Declare one method to get the name , password and user id from previous view.
The header section coding will be like as follows,


         update and delete user  actions are used to update table and delete table. Following codings are used to update a record from database table,




         updating a database is similar to insert record in the data base, only difference is that the query for both are differed.

         To delete particular record from a table, we have to use user_id for that purpose and the coding will be like as follows,          
        

        


         Connect the actions and outlets in both xib window and build and run the application. Output will be as follows,









 
Loading