Pages

Thursday 18 April 2013

Email validation in objective c

If your are designing signup screen in iOS app, you need to validate email provided by user. In this post we will learn ho validate email and show alert if provided email is wrong.

For this we will use NSPredicate and regular expression.



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

}

Now show alert if email is invalid


if(![self validateEmail:[aTextField text]]) {
        // user entered invalid email address
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Enter a valid email address." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show]; 
        [alert release]; //if ARC is disable then write this line otherwise not
 }

Friday 12 April 2013

How to use web service in iOS app

In iOS apps you often need to use web services, today we will learn how to use web service in iOS app. Here we will learn a simple and basic use of web service( A SOAP base service ), in next post we will learn the use of RESTful web service.


What is a web service : A web service (ws) is a media where you request some information from the server and the server processes your request and provides you with the appropriate response.


The response can be in various formats like XML (Extensible mark up language), JSON (JavaScript Object Notation), CSV (comma separated value)
 
In this post we will send a SOAP request to the server 
and reading the output(response) which will be in xml  by using web service provided by w3schools. 
  Step 1 Create a new simple view project in xcode and make design of your project similar to following



Also make properties of required view and IBAction to connect with button.

In first text field we will give value of temperature in Celsius and output will be shown in 2nd text field after pressing button.

   Step 2 For making a call to the webservice running in some server you need to call that service via SOAP request, so to know whats the format of your soap request  check this link where your web method is and their you will get the list of appropriate methods that you may want to use so select the appropriate method, below given are the snaps that will help you out for the web method that I am using.


 Request and response page




Step 3: To execute a web method you need to first need to create the soap body format and pass some of the parameters that are required by that method, and that you can do with the help of the below line


NSString *soapFormat = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                                    "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                                    "<soap:Body>\n"
                                    "<CelsiusToFahrenheit xmlns=\"http://tempuri.org/\">\n"
                                    "<Celsius>%@</Celsius>\n"
                                    "</CelsiusToFahrenheit>\n"
                                    "</soap:Body>\n"
                                    "</soap:Envelope>\n",_txt1.text];


Now we need to specify the location of the web method and that you can do with the help of the NSURL class 

NSURL *locationOfWebService = [NSURL URLWithString:@"http://www.w3schools.com/webservices/tempconvert.asmx"];


Now we need to create a soap header  by using the class NSMutableURLRequest , remember soap body and soap header are two different things, don't mix these two.

NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc]initWithURL:locationOfWebService];
            NSString *msgLength = [NSString stringWithFormat:@"%d",[soapFormat length]];
            [theRequest addValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
            [theRequest addValue:@"http://tempuri.org/CelsiusToFahrenheit" forHTTPHeaderField:@"SOAPAction"];
            [theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"];
            [theRequest setHTTPMethod:@"POST"];
            //the below encoding is used to send data over the net
            [theRequest setHTTPBody:[soapFormat dataUsingEncoding:NSUTF8StringEncoding]];

and finally we will check whether the connection is established or not by creating object of
NSURLConnection class.

NSURLConnection *connect = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
            if (connect) {
                webData = [[NSMutableData alloc]init];
                NSLog(@"Connection Establish");
            }
            else {
                NSLog(@"No Connection established");
            }

In the above code I have took a member of NSMutableData and initialized it, this variable will have the entire xml structure that will be required by us to parse.


Step 4: The NSURLConnection class has delegate method that we must implement so that we can read the xml structure that is returned by the webservice, if you want to see the xml format of the webservice that is returned then it will be provided just below the soap request section.

The delegate methods of NSURLConnection that you will be using are 

didReceiveResponse: In this method you set the mutabledata’s length to zero so that the data present from any previous request is clear

didReceiveData: Append the mutabledata variable with the data received from the webservice

didFailWithError: If the internet connection crashes then write code inside this method to prompt a message to the user for connection failure.

connectionDidFinishLoading: You will be writing code inside this method once the loading of the xml output is done in the mutable data

Here is the code of these methods

#pragma - NSURLConnection delegate method

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

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"ERROR with theConenction");
    //[connection release];
    //[webData release];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
   
    NSLog(@"DONE. Received Bytes: %d", [webData length]);
    self.xmlParser = [[NSXMLParser alloc]initWithData:webData];
    [self.xmlParser setDelegate: self];
    //    [self.xmlParser setShouldProcessNamespaces:NO];
    //    [self.xmlParser setShouldReportNamespacePrefixes:NO];
    //    [self.xmlParser setShouldResolveExternalEntities:NO];
    [self.xmlParser parse];
   
}


Step 5: Now its time to parse the xml for this I have used the NSXMLParser, You may use any xml parser of your choice. In step 4 you can see I have allocated and initialized memory space for the parser and it has some delegate method that I have used to get the work done.

Here is the code of these methods.
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    NSLog(@"found character %@",string);
    [nodeContent appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
    self.finaldata = nodeContent;
    _output.text = finaldata;
    NSLog(@"node %@",nodeContent);
    NSLog(@"final %@",finaldata);
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
   
    if ([elementName isEqualToString:@"CelsiusToFahrenheitResult"]) {
        self.finaldata = nodeContent;
        _output.text = finaldata;
        NSLog(@"did End Element");
    }
    _output.text = finaldata;
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
    NSLog(@"ERROR WITH PARSER");
   
}

 
Now run the code out put will be look like this



Download source code from this  link
    
Remember I used xcode 4.6

iPhone vs Android Phones


For mobile development job sometime interviewer asks for 5 differences between iPhones and  Android phones, so i am writing this blog post to help my all job seeker friends.

01) Closed systems vs. open systems

iOS is developed by apple, and is a closed source mobile offshoot, based on the Mac operating system, optimized for a mobile device

Android is an open source Linux based operating system developed by Google, optimized for mobile devices

02) Security

iPhone has More security. You can blindly rely on iPhone for your data security and other factors.

Android has less security than iPhone.

03) Battery Life

iPhone is having better battery life but battery is not replaceable.

Now a days few android phones are also having good battery life but not that much of iPhone but you can replace battery.

04) Memory

iPhone comes up with inbuilt memory device. (16GB,32GB,64GB)

In android phone mostly we use SD-cards which is main root cause to data leakage and virus infection.

 
05) User Control

iPhone has better user interface and UI is really easy to use.

Android UI is also good but not that much appealing 

06) Google Integration

iPhone is having limited Google integration. In ios6 they have moves Google Maps too.

Android is having all Google product integrated in phone right from Google maps to Google voice. 

07) Vendor Lock-in

iPhone comes up with vendor lockin like AT&T or verizon. Now a days they are allowing unlocked phone but cost is too high.
You can use android phone with any carriers.


08) Hardware support

Apple controls all of its hardware, and it is therefore simple to perform the necessary accessory maintenance.

Google’s Android is simply a platform that functions on different platforms, and doesn’t allow for easy accessory support.

09) Developer support

Apple having really state-of-art development tools with proper documentation which will ease life of apple developer. Only thing is that they are having limited access to the resources or we can say device.

Tools available for android is also good but not that much appealing when we compare it with Apple tools.

10) App Market Policy

Apple is having very strict app approval policy, many time it will take a week or two to review and approve the App on app-store which will maintain quality of app.

Google market approval process is not that much strict and app will get approved in 1-3 days.
11) Cost

iPhone is more expensive than other smartphones in the market.

In Android phone you are having lot of varieties available in different price range. 

12) Device Camera

The iPhone 4S and 5 has the best camera we’ve used yet.

Android phones camera is not that much effective but give you more control of your images before and after the shot. 


 
 

Thursday 11 April 2013

How to create singleton class in objective c

Some time you need to create only one instance of a class and you also want to restrict more than one instance of that class. In this situation you need to create singleton class.

Singleton Class  is a class which has one and only one object.

To create a singleton class in objective C first of all

Create a new class subclass of  NSObject and add the desired properties in .h file.



#import 

@interface User : NSObject
@property (nonatomic, retain) NSString *userName;
@property (nonatomic, retain) NSString *password;
@property (nonatomic, retain) NSString *status;
+ (id)CreateUser;
+ (id)getUser;
@end


Here + sign indicates that methods are static. Its mean we can call these methods without creating instance of class.

Now go to .m file, synthesize  properties and implement method


@synthesize userName;
@synthesize password;
@synthesize status;

static User *user = nil;
#pragma mark Singleton Methods

+ (id)CreateUser {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        user = [[self alloc] init];
    });
    return user;
}
+ (id)getUser {
    return user;
}

Here dispatch_once() is used to execute a block once and only once and it needs pointer to a dispatch_once_t that is used to test whether the block has completed or not.

You can use this code. Call createUser to create user and getUser to get already crated user. 

Tuesday 2 April 2013

Taking image from photo gallery in iOS app

To Take image from photo gallery you will have to implement a method of UIImagePickerControllerDelegate.

First of all go to .h file and defines the  UIImagePickerControllerDelegate.


@interface NewPersonViewController : UITableViewController 


Now go to .m file and implement the delegate method.
This method will be called when you will select your desire photo from image gallery, But right now this method will not called.
There should be an ImageView on your controller on which you will show image after selecting from gallery and make the property of that imageView.


- (void)imagePickerController:(UIImagePickerController *)photoPicker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *selectedImage = [info valueForKey:UIImagePickerControllerOriginalImage];
    [self.selectedImageView setImage:selectedImage];
    [photoPicker dismissModalViewControllerAnimated:YES];
}

   
 
This code will not work according to your desire. You need to write an IBAction which will connect to a button and on pressing button photo gallery will be opened and you will have to write the related code in this method.



- (IBAction)PhotoFromAlbum:(id)sender {
    UIImagePickerController *photoPicker = [[UIImagePickerController alloc] init];
    photoPicker.delegate = self;
    photoPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:photoPicker animated:YES completion:NULL];
}


Now this above delegate method will also be called and whole code will work fine.