google translate in Objective-C - objective-c

I have seen some post which uses google translate web page.
NSString* englishString = [englishInputArray objectAtIndex:i];
NSString *urlPath = [NSString stringWithFormat:#"/translate_a/t?client=t&text=%#&langpair=en|fr",englishString];
NSURL *url = [[NSURL alloc] initWithScheme:#"http" host:#"translate.google.com" path:urlPath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response;
NSError *error;
NSData *data;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Text: %#",result);
I have two questions:
1)the json return from the web page look like this
[[["Bonjour","Hello","",""]],[["interjection",["bonjour","salut","all\u00f4","tiens"]]],"en",,[["Bonjour",[5],1,0,1000,0,1,0]],[["Hello",4,,,""],["Hello",5,[["Bonjour",1000,1,0]],[[0,5]],"Hello"]],,,[],1]
Other than doing string manipulation is there a way to get the the exact translation string alone ie in tis case "Bonjour" alone.
2: Does anybody know if this is this a free service ? Google apis seems to be a paid service. But if you use web page is that a free service.

No. All API's I've used have always been either JSON or XML. There is no reason to use string manipulation when you can just parse the data into a readable structure
If you are looking to use another service that isn't paid, keep in mind there are normally strict limitations. Try something like: SDL https://www.beglobal.com/developers/api-documentation/
Have you read Google's Translate API Documentation?
https://developers.google.com/translate/
For example performing a GET request like so
GET https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&q=Hello%20world
Should return the following response:
{
"data": {
"translations": [
{
"translatedText": "Hallo Welt"
}
]
}
}
With this you can just parse the JSON and display the data

Related

objective c parsing returned json from wcf service

So I asked this question recently and I was able to make it work
objective c calling wcf rest service request
Here's my code
NSString *urlStringRequest = [NSString stringWithFormat:#"http://service.mydomain.com/UserAccountService.svc/UserLogin?id=%#&pword=%#", email, incPassword];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStringRequest]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
id jsonResult = [self parseJsonResult:result];
NSLog(#"Json Result Woop: %#", jsonResult);
the parseJsonResult is exactly the same as the one that was on the link. My problem is though, whenever I would show the jsonResult on the NSLog, it would show the json result which is:
Json Result Woop: {
Authenticated = 0;
Message = "Invalid Log In.";
}
But I'm not really sure how I can go into the variable and retrieve the key and it's value one by one.
I tried to do this:
NSError *jsonParseError = nil;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParseError];
if(!jsonArray)
NSLog(#"Parse error: %#", jsonParseError);
else
for(NSDictionary *item in jsonArray)
NSLog(#"%#", item);
using the result variable but it would just give me the keys.
Not really sure what to do.
JsonResult is already an NSDictionary as evidenced by NSLog showing it like this with curly braces. Just use
jsonResult[#"Message"]
to get to the value for the Message key.

Windows Azure Authentication for Bing Search in Objective-C

On 01.08.12 Bing modified their search api to a Azure, How can I authenticate in Objective-C to use the new bing search api from Azure?
My best guess is to learn from the provided PHP example in the migration word document!! http://go.microsoft.com/fwlink/?LinkID=248077 (Oh god, can't you setup a web page!) or this Java Question - Bing Search API Azure Marketplace Authentication in Java
I'm using ASIHTTPRequest to authenticate with following code.
NSString *queryString = [NSString stringWithFormat:#"'%#'", queryString];
queryString = [queryString urlEncodeUsingEncoding:NSUTF8StringEncoding]; //You'll have to implement url encoding method, preferably in a string category file
NSString *urlString = [NSString stringWithFormat:#"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query=%#&Market='en-US'&$top=50&$format=json", queryString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlString] ];
[request setAuthenticationScheme:(NSString *)kCFHTTPAuthenticationSchemeBasic];
[request setUsername:#"YOUR_KEY_HERE"];
[request setPassword:#"YOUR_KEY_HERE"];
[request setDelegate:self];
[request startAsynchronous];
Please note, no appID required. just instead pass your key as username and password. It is successfully getting the data.
However, can't really convert the data to NSString. tried every encoding but can't get the string from the data. Initial googling says it's UTF-8 encoded. But no success.
For above code to work, you must add ASIHTTP framework.
Another thing is, my guess is passing base64 encoded string with this format your_key:yourkey should also work with basic authentication.
I was able to get it to work using just NSUrlConnection. You must first base64encode
NSString *keyString = [NSString stringWithFormat:#"%#:%#", BING_SEARCH_API_KEY, BING_SEARCH_API_KEY];
NSData *plainTextData = [keyString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainTextData base64EncodedString];
Setup your request
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] init];
[req setURL:[NSURL URLWithString:searchUrl]];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", base64String];
[req setValue:authValue forHTTPHeaderField:#"Authorization"];
Make the request
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
Look at the documentation about how to form searchUrl, and then process data according to the format you specified in $format= (I used json, so mine looks like):
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
I left out error handling, dont forget to add that by checking response as well as error.

Getting a section of an NSString

In my app i'm creating now i use goo.gl's url shortener api to shorted urls. I have it nearly working, I can send the longUrl to retrieve the short one in a NSString but it's in this format:
{
"kind": "urlshortener#url",
"id": "http://goo.gl/something",
"longUrl": "http://somethinglonggggg/"
}
I just wondered if there is a way to just take the id (short url) from that.
Here's what I have so far:
NSString *longURL = urlText.text;
NSData *reqData = [[NSString stringWithFormat:#"{\"longUrl\":\"%#\"}", longURL] dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:#"https://www.googleapis.com/urlshortener/v1/url"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:20];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:reqData];
NSError *err = [[NSError alloc] init];
NSData *retData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:&err];
if([err domain]) return;
NSString *retString = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
if([retString rangeOfString:#"\"error\""].length) return;
NSLog(#" longUrl equals %# ", longURL);
NSLog(#" retString equals %# ", retString);
urlText.text = retString;
You defenitively need to turn that into an NSDictionary (that JSON syntax is for a dictionary, or an object, however you want to call it.
The google API for Objective-C supports JSON parsing to turn the response into objects.
You can find it here.
If all you need is parsing the JSON, I would recommend either JSONkit or TouchJSON.
They both work in very similar ways, you give them the string and they will give you back objects.
The info for the individual usage of the libraries can be found on the readme of the respective project, there you will find how easy to use they are.
You would then acces the different values using:
NSString *short URL = [object valueForKey:#"id"];
This is the best way to interact with REST services.
Hope it helps!

Creating a POST/GET request using Objective -C [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Tutorials for using HTTP POST and GET on the iPhone in Objective-C
Is there away to create an NSArray with the correct information like id = 1, name = #"John", score = 100 then send it and receive a response from the server?
Maybe display it inside an NSLog();
Can anyone help answer this question by linking me to a good tutorial, I don't want to use ASIHTTPRequest either. I know it would be much simpler but if there is away to do something without using a load of prewritten code id rather learn how to make something using the functionality the the foundation framework offers before going off using someone elses classes.
What you're looking for is NSMutableURLRequest and the addValue:forHTTPHeaderField method.
Create the request with the URL you wish to communicate with. Load the values you wish to transmit into the header or into the HTTPBody, set your HTTPMethod and then use a NSURLConnection method to send and receive the response.
As for an array with the information you could simply enumerate through the array and add the values to the HTTPHeaderFields. It really depends on what the server is setup to receive.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165i
Has more information.
NSString *urlString = #"http://yoururl.com";
NSURL *url = [NSUL URLWithString:urlString];
NSMutalbeURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSDictionary *headerInformation = [NSDictionary dictionaryWithObjectsAndKeys:#"1",#"id",#"John",#"name",#"100",#"score", nil];
for (NSString *key in [headerInformation allKeys])
{
[request addValue:[dict valueForKey:key] forHTTPHeaderField:key];
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
// this will perform a synchronous GET operation passing the values you specified in the header (typically you want asynchrounous, but for simplicity of answering the question it works)
NSData *responseData = [NSURLConnection sendSynchronousRequest:request reuturningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#", responseString);
[responseString release];
It might be easier to just use NSData to send a url request and store the response then to reinvent the wheel. Here is some code similar to something in my production project:
+ (NSData *)getProfiles {
NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:#"token"];
// Create string of the URL
NSString *serviceURL = [NSString stringWithFormat:#"http://www.myurlhere.com/getProfiles.php?token=%#", token];
NSLog(#"Service URL : %#", serviceURL);
// Create a NSURL out of the string created earlier. Use NSASCIIStringEncoding to make it properly URL encoded (replaces " " with "+", etc)
NSURL *URL = [NSURL URLWithString:[serviceURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
// Request the url and store the response into NSData
NSData *data = [NSData dataWithContentsOfURL:URL];
if (!data) {
return nil;
}
// Since I know the response will be 100% strings, convert the NSData to NSString
NSString *response = [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
// Test response and return a string that an XML Parser can parse
if (![response isEqualToString:#"UNAUTHORIZED"]) {
response = [response stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
data = [response dataUsingEncoding:NSASCIIStringEncoding];
return data;
} else {
return nil;
}
}
NSLog output:
[Line: 476] +[WebSupport getProfiles]: Service URL : http://www.myurlhere.com/getProfiles.php?token=abcdef0123456789abcdef0123456789

I'm getting a 500 response code from Tumblr's API v2 on video post

I'm able to successfully submit text posts (with 201 responses) but when I change my type parameter to "video" and add appropriate embed and caption parameters, I get a 500 response from Tubmlr.
Their documentation is pretty light on the details of what I need to give for an embed value, but I've tried linking directly to the file, <iframe>, <embed>, with URL escaping using both methods at the W3Schools, and I always get a 500 response.
From what I've seen on other message boards, this is not uncommon, but no one has an answer. The code I'm using is below.
NSString *apiCallURL = [NSString stringWithFormat:#"http://api.tumblr.com/v2/blog/%#/post", self.baseURL];
NSLog(#"API Call URL: %#", apiCallURL);
NSURL *url = [NSURL URLWithString:apiCallURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"utf-8" forHTTPHeaderField:#"charset"];
NSMutableString *body = [[NSMutableString alloc] init]; //Using NSMutableString instead of stringWithFormat to avoid problems with % encoding
[body appendFormat:#"type=video&caption=%#", caption];
[body appendString:#"&embed=EMBED CODE HERE"];
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[body release], body = nil;
[self.authentication authorizeRequest:request];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (error)
{
NSLog(#"Error! \n%#", error);
return;
}
if (data) {
// API fetch succeeded
NSString *str = [[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"Sharing response (%d): %#", [response statusCode], str);
}
The output I get is
Sharing response (500):
The embed code I've been trying to use works through tumblr's web interface and is the URL encoded version of the following:
<embed width="480" height="360" src="http://www.keek.com/embed/decaaab" frameborder="0" allowfullscreen />
You'll likely see an answer from the Tumblr devs on the mailing list here:
https://groups.google.com/forum/#!topic/tumblr-api/id_pKWwPcro
It seems to be a problem on tumblr's end.