Google Translate API for iPhone - UTF8 problem in Chinese Translation - iphone

I've tested a workable translation API url by:
http://translate.google.com/translate_a/t?client=t&text=%E5%BB%A3%E5%A0%B4&langpair=zh|zh-CN
And it returns the correct result as the following which is in JSON format:
{"sentences":[{"trans":"广场","orig":"廣場","translit":"Guǎngchǎng"}],"src":"zh-CN"}
However, when I try to use this function in XCode, I experienced this problem ...
Here is my code:
NSData *data;
NSString *urlPath = [NSString stringWithFormat:#"/translate_a/t?client=t&text=%#&langpair=zh|zh-CN",qText];
NSURL *url = [[NSURL alloc] initWithScheme:#"http"
host:#"translate.google.com"
path:urlPath];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response;
NSError *error;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; //Problem's here. It returns nil.
NSLog(result);
Initially I guessed it's encoding problem so I tried other encoding as well (NSISOLatin1StringEncoding) , but I got wrong answer: {"sentences":[{"trans":"ã ","orig":"ã ","translit":"Tu¨¯ "}],"src":"zh-CN"}
Does anyone know how to solve this problem? Thank you very much!

Have you tried checking the error object? If an error occurs, this call will just set the error object and continue - it won't crash/throw like a normal error.
Try something like this after the sendSynchronousRequest call:
if (error != nil)
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
This should give more details if an error occurred.

Related

GData adding \ to end of element

Getting a parsing error after connecting to web service. I won't post that problem (yet) as I'm running down possible problems.
One that I noticed with displaying the individual GData elements, is that it is putting a "\" at the end of the element.
Example of what it should look like:
"Element1"xxxxx""/Element1"
Example of what it doing:
"Element1/"xxxxx""/Element1"
The quotes represent the less than and greater than symbols... I couldn't figure out how to get them to show here.
Have no idea what is causing this... any idea why?
Sample code:
GDataXMLElement *sellerElement = [GDataXMLNode elementWithName:#"Element1"];
GDataXMLElement *credElement = [GDataXMLNode elementWithName:#"Element2"];
[sellerElement addChild:credElement];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:path] cachePolicy:NSURLCacheStorageAllowedInMemoryOnly timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"733" forHTTPHeaderField:#"COMPATIBILITY-LEVEL"];
[request setValue:#"xxxxxxxxx" forHTTPHeaderField:#"API-DEV-NAME"];
[request setValue:#"yyyyyyyyy" forHTTPHeaderField:#"API-APP-NAME"];
[request setValue:#"GeteSomething" forHTTPHeaderField:#"API-CALL-NAME"];
[request setValue:#"0" forHTTPHeaderField:#"API-SITEID "];
[request setValue:#"text/mxl" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[xmldoc XMLData]];
NSURLResponse *response = nil;
NSError *error;
NSData *data = nil;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([data length] > 0) {
GDataXMLDocument *xmldoc = [[GDataXMLDocument alloc] initWithData:data options:0 error:&error];
NSLog(#"Recieved %#", xmldoc);
}
After days of messing around with this, I found that it was all along my error.
Putting an NSLOG on sellerElement credElement, gives me the results above.
The problem is that it was not complete, in that I didn't look at the results after adding (addChild) elements together, where the xml is all put together.
After putting a NLSOG on sellerElement, the results I was expecting was shown.

How to execute URL requests from an iOS application?

I want to send the following request to the server. The server already knows what to do with it, but how can I send it?
http://www.********.com/ajax.php?script=logoutUser&username=****
For a synchronous request you would do the following:
NSURL *url = [NSURL URLWithString:#"http://www.********.com/ajax.php?script=logoutUser&username=****"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//send it synchronous
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// check for an error. If there is a network error, you should handle it here.
if(!error)
{
//log response
NSLog(#"Response from server = %#", responseString);
}
Update: for doing an asynchronous request please refere to this example
You can do:
NSString *resp = [NSString stringWithContentsOfURL:url usedEncoding:enc error: &error];

Wunderground API json lookup on iPhone

Never touched json before. I'm trying to access some variables within the Wunderground weather API for Melbourne. For example, let's say I want to access the "wind_dir":"East" variable. This is my code thus far:
NSString *urlString =
[NSString stringWithFormat:
#"http://api.wunderground.com/api/key/geolookup/conditions/forecast/q/-33.957550,151.230850.json"];
NSLog(#"URL = %#", urlString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *weatherInfo = [parser objectWithString:json_string error:nil];
for (NSDictionary *weatherString in weatherInfo)
{
NSLog(#"some weather info = %#", [[[weatherString objectForKey:#"response"] objectForKey:#"current_observation"] objectForKey:#"wind_dir"]);
}
My code reaches the for loop and crashes with this error: -[NSCFString objectForKey:]: unrecognized selector sent to instance.
I'm not 100% sure what's causing the crash, and whether my path to the "wind_dir" variable is correct, though they could well be the same problem.
Thanks in advance for any help.
either the "response" property or the "current_observation" propery is string and not dictionary.
the error you are getting is that you are trying to call "objectForKey" on a string.
after looking at the result of the API, it seems that you are not getting an array.
You should do something like this:
NSDictionary *weatherInfo = [parser objectWithString:json_string error:nil];
NSLog(#"some weather info = %#", [[weatherInfo objectForKey:#"current_observation"] objectForKey:#"wind_dir"]);
instead of your for statement.

Google Translate API in Xcode: NSMutableURLRequest returning NULL, not expected result

when I run the following google translation API URL http://translate.google.com/translate_a/t?client=t&text=Hello&langpair=en|fr it returns the correct result.
However, when I try to use the following in Xcode it returns (Null). I would appreciate any help or insight you can provide.
NSString *urlPath = [NSString stringWithFormat:#"/translate_a/t?client=t&text=%#&langpair=en|fr",#"Hello"];
NSURL *url = [[NSURL alloc] initWithScheme:#"http" host:#"translate.google.com" path:urlPath];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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:NSUTF8StringEncoding];
NSLog(#"Text: %#",result);
Your encoding is incorrect. change it to NSASCIIStringEncoding.
I just fixed your code and ran it locally and it worked like a charm...
here are the results
[[["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]

NSURLErrorBadURL error

My iphone app called Google Local Search(non javascript version) to behave some search business.
Below is my code to form a url:
NSString *url = [NSString stringWithFormat:#"http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=%#", keyword];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[[NSError alloc] init] autorelease];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
When the keyword refers to english characters, it works fine, but when refers to chinese characters(encoded in UTF8, such as '天安门' whose UTF8 code is 'e5a4a9 e5ae89 e997a8'), it will report NSURLErrorBadURL error(-1000, Returned when a URL is sufficiently malformed that a URL request cannot be initiated). Why?
Then I carry out further investigation, I use Safari and type in the url below:
http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=天安门
It also works, and the output I got from Macsniffer is:
/ajax/services/search/local?v=1.0&q=%E5%A4%A9%E5%AE%89%E9%97%A8
So I write a testing url directly in my app
NSString *url = [NSString stringWithFormat:#"http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=%E5%A4%A9%E5%AE%89%E9%97%A8"];
And what I got from the Macsniffer is some other thing:
/ajax/services/search/local?v=1.0&q=1.687891E-28750X1.417C0001416CP-102640X1.4CC2D04648FBP-9999-1.989891E+0050X1.20DC00184CC67P-953E8E99A8
It seems my keyword "%E5%A4%A9%E5%AE%89%E9%97%A8" was translated into something else. So how can I form a valid url? I do need help!
Have you tried encoding the search string:
NSString* escapedKeyword = [keyword stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];