In this tutorial we are going to see three things
1) How to consume RESTfull Services in iOS.
2) How to parse JSON response.
3) Google Translate APIs.
Basically there are two types of web-services .
1) SOAP services.
2) REST Services.
SOAP services deal with SOAP protocol. It uses xml . While using SOAP services you have to follow the set of strict rules to create and receive SOAP messages. We would talk about that in details in the SOAP services post.
As now a days the most widely used services are REST services , we will focus on that in this tutorial. Some advantages using REST services are as below
1) It can use JSON . ( Very light weight way for data communication compared to XML )
2) Easy to implement .
3) Parsing JSON is quit easy.
4) Because of all the above , you achieve the quick response time .
( Note : Again whether to go for REST or SOAP completely depends on the server side programmer who is creating the web services . If you are responsible for both side work ( iPhone and sever side coding ) then REST service with JSON would almost solve the purpose. )
Ok that is enough talk about the web services. If you want you simply google the terms RESTfull web services or SOAP web services to know more about them .Lets get to the implementation part.
Now in this tutorial we are going to user google's REST services for language translation. I am talking about the Google Translate APIs. Our final output will look like below screenshot.
User will be entering some text in English . User will have some choices of languages to choose for the translation. When user presses the translate button , we will do the web service consuming task and will display the translated text in the label at the bottom.
We are going to parse the JSON in this project so lets download the JSON parsing library for our project. The most widely used in iOS is SB-JSON. Its the third party library for parsing JSON text. Download the files from below link.
Download the file , save this on your mac as you would be needing this lot many times in the future projects. Ok , next expand the zip . You can see some folders like classes , examples etc.. What we need is the classes folder .You can see a number of files in the classes folder. Drag all these files into the Xcode project that you have created . When you add the files to the project , make sure the copy files if Needed checkbox is checked. This will actually copy all the files to your project.
(Note : You can just create a group in the project to add all these files so that it would look cleaner and is always better to manage ).
You can now build the project just to make sure that JSON parser files have been successfully integrated with the project.
Next , lets add a new file that is UIViewController subclass . I have named it MyViewController with the XIB for user interface . The xib view will look like this.
The view contains following controls.
- A picker for displaying different languages.
- A text filed for user to enter the text ( English text ).
- A button.
- A label to display the translated text.
Lets go to MyViewController.h. It should look like this.
You can see three outlets , one for each picker, textField and valueLabel. There are two methods
This method would be invoked on the translate button touch up.
This method would be used to parse the JSON response.
We have got two arrays langNames and langCodes. langNames array will store the languages names like Hindi , French , Arabic etc. langCodes array will store the corresponding language codes like "hi" for Hindi , "fr" for french etc..
Lets have a loot at the initWithNibName method.
Implement the following textField and UIPickerView datasource and delegate methods. You can simply copy these in your MyViewController.m
#pragma TextField Delegate Methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField
#pragma Picker Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
- (NSInteger)pickerView:(UIPickerView *)pickerViewnumberOfRowsInComponent:(NSInteger)component
return [langNames count];
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)rowforComponent:(NSInteger)component
return [langNames objectAtIndex:row];
Now this will display the languages in the picker. Next Lets have a look at the method that would be called on translate button touch.
// get theselectec langauge number and with that fetch the correposing language code fromthe langCodes array.
int selected = [langPicker selectedRowInComponent:0];
NSString * langCode =[langCodes objectAtIndex:selected];
// Below isthe webservice URL. It takes two parameters in the query string , 1) text to betranslated and then langpair=en|%@" from en to %@ language.
// q=%@ ( for text to be translated )
// v=1.0 (this is the only version for google translate api available , so no worries).
//langpair=en|%@ ( It is of the form from_language|to_language ).
NSString *serviceURLString = @"https://ajax.googleapis.com/ajax/services/language/translate?q=%@&v=1.0&langpair=en|%@";
// Here wereplaces the placeholder with the actual values.
NSString *serviceURLFinalString = [NSString stringWithFormat:serviceURLString,englishField.text,langCode];
// Here wereplaces the empty spaces , '|' , etc characters with correspoing %escapes.( wecan not have a black space in the URL )
serviceURLFinalString =[serviceURLFinalString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// Create aNSURL object from the string.
NSURL *serviceURLFinal = [NSURL URLWithString:serviceURLFinalString];
// fetchingthe contents from the string.
NSString * response =[NSString stringWithContentsOfURL:serviceURLFinalencoding:NSUTF8StringEncoding error:nil];
NSLog(@"Response: %@ ",response);
The above method is well commented , so you can read the comments to understand what we are doing exactly. We are logging the response on the console. So for the time being you can comment the line [self parseJSONString:response]; and simply check the what response we are getting on the console . If I enter a text "We are iPhone programmers." then the response we get is a JSON response as below.
Now our next task would be to parser this JSON and display the translated text in the value label.
The method parseJSONString does the work. Lets have a look at the implementation.
NSDictionary * responseDic= [string JSONValue];
if([[responseDic objectForKey:@"responseStatus"] intValue] == 200 )
NSString * value =[[responseDic objectForKey:@"responseData"] objectForKey:@"translatedText"];
valueLabel.text = value;
valueLabel.text = @"Pleaseenter a valid English text !!!";
Explanation : The above method parses the JSON response string.
[string JSONValue]; returns a dictionary of the JSON response. First we check if the reponseStatus is 200 or not . If it is 200 that means we have got the proper response. So next fetch the translated text and assign it to the value label.
Run the program and test it with different languages . Lets have a look at the output.
Hope this post helps you all in handling restful services , parsing JSON and integrating the Google Translate APIs. If you have any doubts or issues , feel free to post them as comments. Keep checking the blog for more posts soon !!!