Google Translate and iPhone apps

The Cocoa and Cocoa Touch frameworks has a really nice function for acquiring a localized string NSLocalizedString(). Just pass in a key and you are done, for strings that are known at least. Sometimes you are getting unknown strings from a data source not under your control, strings representing just a fraction of the text in your UI. Leaving this text in it’s source language looks weird, and skipping translation all together just feel wrong.

Google Translate to the rescue

Turns out that Google Translate has a nice AJAX API, feed it a URL request and get a JSON response. Admittedly the translations are not always perfect, even quite humorous at times, but good enough if you provide the user a warning.

So let us create a sibling to NSLocalizedString() called CWTranslatedString(). It should take two arguments; the string to translate, and the source language ISO code. We should also be able to get the users currently selected language, that will be used as the destination language when translating. So this is our header:

NSString* CWCurrentLanguageIdentifier();
NSString* CWTranslatedString(NSString* string, NSString* sourceLanguageIdentifier);

Currently your iPhone application must be terminated in order for the user to change the language. And even when Apple adds multitasking for third-party apps we can assume the user do not go about and switch languages too often, so we let CWCurrentLanguageIdentifier() cache the language code:

NSString* CWCurrentLanguageIdentifier() {
    static NSString* currentLanguage = nil;
    if (currentLanguage == nil) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSArray* languages = [defaults objectForKey:@"AppleLanguages"];
        currentLanguage = [[languages objectAtIndex:0] retain];
    }
    return currentLanguage;
}

Now for the CWTranslatedString() function. The JSON response from Google Translate is well formatted with no line breaks, so let’s not bother with a proper JSON-parser. We can use a simple NSScanner, and just return the source string for any unexpected result. We also short circuit and return the source string if the source and dest language as equal.

NSString* CWTranslatedString(NSString* string, NSString* sourceLanguageIdentifier) {
    static NSString* queryURL = @"http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%@&langpair=%@%%7C%@";
    if (sourceLanguageIdentifier == nil) {
        sourceLanguageIdentifier = @"en";
    }
    if ([sourceLanguageIdentifier isEqual:CWCurrentLanguageIdentifier()] || string == nil) {
        return string;
    }
    NSString* escapedString = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString* query = [NSString stringWithFormat:queryURL,
                       escapedString, sourceLanguageIdentifier, CWCurrentLanguageIdentifier()];
    NSString* response = [NSString stringWithContentsOfURL:[NSURL URLWithString:query]
                                                  encoding:NSUTF8StringEncoding error:NULL];
    if (response == nil) {
        return string;
    }
    NSScanner* scanner = [NSScanner scannerWithString:response];
    if (![scanner scanUpToString:@""translatedText":"" intoString:NULL]) {
        return string;
    }
    if (![scanner scanString:@""translatedText":"" intoString:NULL]) {
        return string;
    }
    NSString* result = nil;
    if (![scanner scanUpToString:@""}" intoString:&result]) {
        return string;
    }
    return result;
}

And that is it. Not perfect, but nice to have.

This Post Has 13 Comments

  1. Hi Fredrik,

    So, you’re basically changing the way you get a translated string back instead of a .strings file to use Google Translate. It seems to make sense for the most part. What’s the performance overhead on the difference between using Google Translate vs a static .strings file? Also, it does add the requirement of having an internet connection, so it could be less viable? Does it default to English or some language if internet is accessible or does it just prevent your app from launching/functioning?

    1. No I would not call it changing the way. You should not use Google translate as the normal means of translating your app. For that you need professional translators. Only use it for dynamic text, that you can not provide statically when distributing the app binary.

      Yes the code I provided do require an internet connection. You could add network availability checks and return the original string if needed. But since this method should only be used for translating unknown text that you got from the network, assuming a network is available is a quite valid asumption.

  2. I am quite sure that Google’s licensing terms don’t allow you to use this in paid apps. Not sure whether it would be fine to use in free apps. I suspect so, but better read the licensing terms first in detail!

  3. Thanks alot for this. this was very helpful, and unlike most code snippets on blogs. it actually runs smoothly.

  4. “Hendrik on 01.16.10 at 23:09

    I am quite sure that Google’s licensing terms don’t allow you to use this in paid apps. Not sure whether it would be fine to use in free apps. I suspect so, but better read the licensing terms first in detail!

    Why not, it’s just an http request, if translate responds to the open http request can ‘licensing terms’ even limit this? Does google translate allow the use of http requests from paid browsers like opera or internet explorer?

  5. Buciiii

  6. I’ve tried many times, but has not been successful and hard at all, what is wrong. why? thanks for the information

  7. I appreciate what this tteam is doing… nobody believed me, I got sick of hearing myself! i still believe it was brought back by, sadly my now ex because hes lied for 3 months about what, or “who” hes been doing bit thhis softens blow!

  8. Amazing! Its truly remarkable paragraph, I have got
    much clear idea concerning from this piece of writing.

  9. Hi Fredrik, thanks for sharing such an useful information. Really a great help. Awaiting for more such useful blogs regarding google translate & iphone apps.

Leave a Reply

Close Menu