Thursday, 5 June 2014

What is SWIFT?




SWIFT is a new programming language introduced by apple at WWDC 2014 for Cocoa and Cocoa Touch. The Cocoa and Cocoa Touch frameworks are the nuts and bolts that power OS X and iOS.
The language is much more concise. If you have a background in any C based language, you can easily work with this. 

Why We Need SWIFT?

After introducing the Macintosh computer by Apple, Mac apps have been built using Objective C. Objective C is a programming language that was introduced in 1983. Objective C has evolved tremendously over the years, but certain features of the language have become outdated as the nature of the devices we use has shifted.

Back in 1983, we did not have smart phones so Objective C wasn’t developed with iPhones or touch interfaces in mind, and to compensate, Apple has built more and more new frameworks on top of Objective C. Instead of continuing to build frameworks on top of an older programming language, Apple introduced SWIFT.

The Five Key Swift Improves On Objective-C

In developer documentation, Apple highlights five key areas in which Swift over takes Objective-C.

Safe

Safe does not mean viruses protected safe mean Stable Wait hold on, have Ever had an iPhone app disappear with a black flash and end up back on your home screen? That’s a crash, and Swift is more stable than previous code, so that means fewer crashes on your iPhone, iPad, iPod, and other new iDevices 

Modern

“Modern” means features which will be loved by developers but nothing for users. “Modern” also refers to new programming methods that have been popularised in recent years. Swift can accomplish more in a single line of code than Objective-C could in multiple lines of code.

Powerful

“Powerful”, mean Intelligent. In Objective C, programmers have to include lots of Frameworks or Libraries to perform common tasks, because that core functionality wasn’t included within Objective C. Swift has many of those functions built in, so there is no need to pull in external files to get things done :)

Interactive

“Interactive”, does not mean user Interactive with their device. it’s referring to the developer’s experience while coding. With Swift, developers see changes they make instantly rather than having to recompile a program every time they make a change. Its really cool :P

Fast

I will explain “Fast” in two ways.
1- “Fast” means code execution will be fast. 
2- “Fast” also means that developers will have to do a lot of less work as compared to Objective C. Also developers with smaller budgets will now be able to develop apps/games that look and feel like the big-budget apps/games.

Technical point of view Here are some features of SWIFT that I note.

Classes 
SWIFT supports classes which are key feature of OOP. SWIFT also supports single inheritance and also structs without inheritance.
Properties
Classes can have Properties. Properties have get and set methods like Objective C 
Types 
Swift uses var, constants and types can be added optionally.
Operator overloading
SWIFT supports operator overloading similar to c++. 
Range  
A Range is an expression in the form 4…7 and can be used in control statements like if, switch, loops and also in array operations. Eg. replace element 4 to 7 with another element. The feature seems to be inspired by Python.
Tuples
A tuple in the form of (code, message, <more elements>) can be used as a sort of a lightweight object.
Closures
Closures are basically lambda expressions that allow to inline code fragments.
Switch statement
The switch statement is quite powerful. It has no default fall through and is able to switch on a multitude of conditions like ranges, list of elements, boolean expression, enums etc.
Extensions 
An extension is probably pretty close to a prototype in Javascript or a C# extension as it allows to retrofit an existing class with new methods or properties.
Functions
SWIFT supports functions like any other language.
Optional Chaining
Protects from exceptions when calling multiple methods and properties in a chain where one call participant would return “nil”.





Monday, 26 August 2013

Hiding keyboard on pressing return key in iOS

10 month ago when I start iOS programing this was a confusing task for me to hide keyboard on pressing return key. Hiding keyboard by taping background was much more confusing, but actually these two tasks are very easy So today we will learn both of these.

I am assuming that you have created a single view application in xCode.

Hide keyboard by pressing return key.

1- Make  the screen like this.




2- Go to .h file and implement UITextFieldDelegate protocol like this.



#import 

@interface ViewController : UIViewController<UITextFieldDelegate>

@end

 }

3- Now make the property for text field(if you know ho to make property then go to step 4).
 Open assistant editor and press ctr + left click and drop at .h file like below.

A new small window will be opened like this.






Give name in the name box. After this a property will be made and .h file look like this.



4-  Now to go to .m file and set the delegate of text field.



- (void)viewDidLoad
{
    [super viewDidLoad];
 
    self.textField.delegate=self;
}

5- Now finally implement the textFieldShouldReturn method like this.


-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


Now run the app and write something in text field then press return key it will work fine.
If you want to do same with other text field then just make property of text field and set delegate just, it will work.

I hope this post will help you, any comments good or b ad are always welcome. you can also request me for a tutorial.

Friday, 24 May 2013

Adding custom font in ios app

The addition of custom font ios app is very easy and hardly take 2 mints. When first time my team lead gave me this task I was thinking it will be a difficult task and take minimum 30 mints, but when I start it take hardly 2 mints. So do not worry with the name "custom font" just start it.....

Step 1

Download your required font file having .otf extension. In this post I am using " MyriadPro Bold" which can be download from this link.
Add the downloaded file in your project. After that  go to info.plist file and add "Fonts provided by application".



Now add new item under "Fonts provided by application" and give the name of font file with extension.



Step 2

Now its time to write code, go to .m file and write the code of setting font.





 font=[UIFont fontWithName:@"MyriadPro-Bold" size:17];
 [self.label setFont:font];



That's it. Does it take more than 2 mint???????


Note: Make sure that font file (which you have included in your project) is also present in bundle resources. Mostly xcode automatically include it but some time it does not, In this case you will have to do it manually.

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.