By Adam Nagy
Another sample app I created for my AU presentation was one using REST translator services.
First I thought of using the Google translation service. So I went on this website https://developers.google.com/translate/v2/using_rest and checked the URL I needed to access.
You can get back all the supported languages and their codes using https://www.googleapis.com/language/translate/v2/languages?key=<GOOGLE_APIKEY>&target=en
As you can spot it in the above link we'll need to get an API KEY from Google before we can make this call. So I registered on their site and got it.
Now we can fill up an NSMutableArray with the list of supported languages:
NSError * err = nil;
NSString * urlString = [NSString stringWithFormat:@"https://www.googleapis.com/language/translate/v2/languages?key=%@&target=en",
GOOGLE_API_KEY];
NSURL * url = [NSURL URLWithString:urlString];
NSMutableURLRequest * req =
[NSMutableURLRequest requestWithURL:url];
// Using synchronous request just to keep things simple
NSData * data = [NSURLConnection sendSynchronousRequest:req
returningResponse:nil error:&err];
NSDictionary * json = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&err];
jsonLanguages =
[[json objectForKey:@"data"] objectForKey:@"languages"];
Once you converted the response Json string into a tree of NSDictionary's and NSArray's using NSJSONSerialization, you can easily check its content to see how you can retrieve specific information from there by using po in the Console window and passing in the variable's name:
I created the following user interface. Started with a Single View Application and placed a Text Field, a Label, a Button, and a Picker View on the view in the storyboard. Then hooked those up in my code the usual way (like in this article), by Ctrl-dragging them onto my code file, ViewControlller.h
- In the text field the user will be able to type the text they want to translate
- In the picker view we'll list the available languages that the user can select from
- And when the button is clicked the label will show the translated text
All that is left is doing the translation. I've already implemented the translation part using the Google service when I realized that it does not provide any number of translations for free and so always returns an error - still, I kept the code in the attached project. Since this was just meant to be a sample I did not want to spend money on it and so looked for a free service. One of those was at http://www.frengly.com. There as well you need to register to get a user name and password that you need to use for the translation, but at least it's for free.
Now when the button is clicked I can do the following:
- (IBAction)translate:(id)sender
{
NSError * err = nil;
NSInteger selection = [self.languages selectedRowInComponent:0];
NSDictionary * language = [jsonLanguages objectAtIndex:selection];
NSString * languageCode = [language objectForKey:@"language"];
NSString * urlString = [NSString stringWithFormat:@"http://www.syslang.com/frengly/controller?action=translateREST&src=en&dest=%@&text=%@&username=%@&password=%@",
languageCode,
[self.original.text
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
SYSLANG_USER_NAME,
SYSLANG_PASSWORD
];
NSURL * url = [NSURL URLWithString:urlString];
NSMutableURLRequest * req = [NSMutableURLRequest requestWithURL:url];
NSData * data = [NSURLConnection sendSynchronousRequest:req
returningResponse:nil error:&err];
// Create and init NSXMLParser object
NSXMLParser * nsXmlParser = [[NSXMLParser alloc] initWithData:data];
// Create and init our delegate
XmlParser * parser = [XmlParser alloc];
// Set delegate
[nsXmlParser setDelegate:parser];
// Parsing...
BOOL success = [nsXmlParser parse];
// Test the result
if (success)
self.translation.text = parser.translation;
}
Unfortunately, this service sends the information in xml format, so I needed to create a parser for that. I like checking what is available natively, without using 3rd party libraries, so I gave NSXMLParser a try.
XmlParser.h
//
// XmlParser.h
// MyAWS
//
// Created by Adam Nagy on 06/11/2012.
// Copyright (c) 2012 Adam Nagy. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface XmlParser : NSObject <NSXMLParserDelegate>
@property (strong, nonatomic) NSString * translation;
@end
XmlParser.m
//
// XmlParser.m
// MyAWS
//
// Created by Adam Nagy on 06/11/2012.
// Copyright (c) 2012 Adam Nagy. All rights reserved.
//
#import "XmlParser.h"
@implementation XmlParser
@synthesize translation;
static bool translationTag = false;
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:@"translation"])
translationTag = true;
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if (translationTag)
{
if (!translation)
translation = [NSString stringWithFormat:@""];
translation = [translation stringByAppendingString:string];
}
}
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:@"translation"])
translationTag = false;
}
@end
Project is attached here: Download Translator_2012-12-05
Note: the code only works if you first register for the above mentioned services and then fill these variables with your credentials: GOOGLE_API_KEY, SYSLANG_USER_NAME and SYSLANG_PASSWORD
Comments
You can follow this conversation by subscribing to the comment feed for this post.