Google Translate Tutorial for iOS: How To Translate Text With Google Translate and JSON on the iPhone

A Google translate tutorial on how you can easily use Google Translate to translate text into different languages on the iPhone. By Ray Wenderlich.

Leave a rating/review
Save for later
Share

Funny Translation App We Will Build

Funny Translation App We Will Build

Google Translate provides a really neat API that you can use to quickly and easily use in your apps to translate text between tons of different languages.

In this Google Translate tutorial, we’re going to show you how you can use this API from your iPhone app to translate text a user enters in, back and forth from Japanese to English, until a “final match” is found, similar to the amusing Translation Party web page created by Will Carlough and Richard Boenigk.

This Google Translate tutorial will provide an introduction to JSON as well as the Google Translate APIs specifically. It is based upon an excellent tutorial on using JSON on the iPhone by Dan Grigsby at MobileOrchard (we miss you Dan!), but has more details on JSON for those who are new to the concept and information about the Google Translate API specifically.

What is JSON?

JSON is a simple human readable format that is often used to send data over a network connection.

For example, if you have an array of three strings, the JSON representation would simply be:

["test1", "test2", "test3"]

If you have a Pet object with member variables name, breed, and age, the JSON representation would simply be:

{"name" : "Dusty", "breed": "Poodle", "age": 7}

It’s that simple, which is why it’s so easy and popular to use. For the full spec, which can be read in just a couple minutes, check out the JSON format home page.

What is a JSON web service?

Many third parties such as Google or Yahoo! provide web services that return JSON formatted data when you visit a URL with a specified query string.

For the case of Google Translate’s web service, you can translate some text by issuing a GET request to the following URL:

http://ajax.googleapis.com/ajax/services/language/translate

When you issue the GET request, you need to pass some parameters to the web service. You do this by appending a query string to the end of the URL. In short, you begin the query string with a “?” and then add a sequence of “name=value” pairs, separated by the “&” symbol.

The web service defines which arguments need to be passed to the web service. For Google Translate, they have a nice definition of the Google Translate parameters that you can check out.

But the synopsis is to translate some text with Google Translate, you need to pass three arguments:

  • v: Short for “version”, and should always be set to 1.0
  • q: Short for “query”, and should be set to the text to translate.
  • langpair: Short for “language pair”, and should be set to a string containing the pair of two-letter language codes for the languages to translate, separated by a “|” sign.

Note that the values for each of these arguments needs to be escaped by adding percent escapes, according to the rules of URL encoding. For example, the “|” sign is escaped to “%7C”. Luckily, we don’t have to worry about this on the iPhone because there’s there’s a function in NSString that we can use to easily perform the required escaping.

So, the full URL with the query string to translate some text would look something like this:

http://ajax.googleapis.com/ajax/services/language/translate?q=where's%20
    the%20bathroom?&v=1.0&langpair=en%7Cja

Once you perform a GET request with that URL, Google will respond with a string that looks something like this:

{"responseData": {"translatedText":"\u3053\u3053\u3067\u3001\u30d0\u30b9\
    u30eb\u30fc\u30e0\u3068\u306f\uff1f"}, 
    "responseDetails": null, "responseStatus": 200}

Based on what we know about JSON, this means that there is an object with three member variables: “responseData”, “responseDetails”, and “responseStatus”. In the case of “responseData”, that is a sub-object with a member variable of “translatedText”. The value of “translatedText” is just our escaped (Japanese in this case) string.

Ok – enough background, let’s get started!

Adding a JSON Framework to our project

Although you could write the code to parse this string yourself, it’s much easier and less error prone if you use one of the excellent libraries available to do so. For this Google Translate tutorial, we are going to use the Open Source Objective-C JSON framework developed by Stig Brautaset. So go ahead and visit site now and download the latest version of the framework.

Once you have it downloaded, make a new View-based Application in XCode and name the project GoogleTranslate. Right click on “GoogleTranslate” under “Groups & Files”, and click “Add\New Group” and name the group “JSON”. Then open the disk image of the JSON framework that you downloaded, open the JSON folder inside, and drag all of the files in that folder to the new “JSON” group you created in XCode. When the dialog pops up, verify that “Copy items into destination group’s folder (if needed)” is checked.

Next, open up GoogleTranslateViewController.m under Classes and add the following import to the top of the file:

#import "JSON.h"

Compile your project – if it compiles OK you’ve successfully integrated the JSON framework!

How the JSON Framework Works

The main class in the JSON Framework is named SBJsonParser. Once you get the JSON results from the web server, you pass it to the SBJsonParser via the objectWithString method. The parser will do all of the work to parse the string and convert the values into the most appropriate Objective-C type.

The JSON datatypes are converted to Objective-C types as follows (from SBJsonParser.h):

  • Null -> NSNull
  • String -> NSMutableString
  • Array -> NSMutableArray
  • Object -> NSMutableDictionary
  • Boolean -> NSNumber (initialised with -initWithBool:)
  • Number -> NSDecimalNumber

So in our case, the response from Google Translate would be converted into an NSMutableDictionary with three keys: responseData, responseDetails, and responseStatus.

The one we care about the most is responseData. It’s actually another NSMutableDictionary with just one key: translatedText. And translatedText is a simple NSString – the result we’re looking for!

Ok we’re really done with background information for real now! Let’s set up our interface.

Creating the Interface

Before we begin, let’s set up some member variables in our GoogleTranslateViewController class so we can hook them up with Interface Builder shortly. Open up GoogleTranslateViewController.h and edit the file to look as follows:

#import <UIKit/UIKit.h>

@interface GoogleTranslateViewController : UIViewController {
    IBOutlet UITextView *textView;
    IBOutlet UITextField *textField;
    IBOutlet UIButton *button;
}

- (IBAction)doTranslation;

@end

Now expand the Resources tab and open up the GoogleTranslateViewController.xib. Open up the main view, and use the library to add a text field view, button, text view, and label to look like the following:

Layout in IB for our View

In the properties, remove all of the text in the Text View, and unclick “Editable”. Then, control-drag from the File’s Owner to the text view, text field, and button in the XIB window and connect them to their outlets. Finally, control drag from the button back to the File’s Owner to connect the doTranslation callback.

Save your XIB and compile and run the project to make sure that everything shows up OK so far. But don’t click the button yet, we haven’t actually written the callback! :]