iPhone SDK - Google TTS and encoding - iphone

I am developing a text-to-speech iphone app that support multi-languages.
Here is my request URL
requestUrlStr = #"http://www.translate.google.com/translate_tts?tl=en&q=hello";
for english the above url has no problem
but for Chinese
requestUrlStr = #"http://www.translate.google.com/translate_tts?tl=zh-TW&q=你好";
I know the above url will give 'Bad URL', so I used follow method to encode the string into UTF-8
requestUrlStr = [requestUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
It will become
http://www.translate.google.com/translate_tts?tl=zh-CN&q=%E4%BD%A0%E5%A5%BD
Then the Google TTS cannot recognize this Chinese text.

You have to pretend to be a User-Agent other than the default (appName, etc) in your NSURLRequest. Try this (I use Greek language) ...
NSString* userAgent = #"Mozilla/5.0";
NSURL *url = [NSURL URLWithString:[#"http://www.translate.google.com/translate_tts?tl=el&q=Καλημέρα"
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease];
[request setValue:userAgent forHTTPHeaderField:#"User-Agent"];
NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
[data writeToFile:#"/var/tmp/tts.mp3" atomically:YES];
UPDATE 2017
Since our favorite companies enjoy to update and deprecate things, here is the above example as it should be now...
NSString* text = #"καλημέρα";
NSString* lang = #"el";
NSString* sUrl = [NSString stringWithFormat:#"https://translate.google.com/translate_tts?q=%#&tl=%#&client=tw-ob", text, lang];
sUrl = [sUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:sUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"Mozilla/5.0" forHTTPHeaderField:#"User-Agent"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:nil
delegateQueue:[NSOperationQueue mainQueue]];
[[session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[data writeToFile:#"/var/tmp/tts.mp3" atomically:YES];
}
] resume];
The ...delegate:nil delegateQueue:[NSOperationQueue mainQueue] can be omitted.

Related

Facebook curl like post request using open graph

I want to create the like button in my iOS app by using
curl -X POST \
-F 'access_token=USER_ACCESS_TOKEN' \
-F 'object=OG_OBJECT_URL' \
https://graph.facebook.com/[User FB ID]/og
.likes given by Open graph api.
For it I have made post request i.e.
NSString *stringurl=[NSString stringWithFormat:#"{access_token=AAAE08AxGmwghghghOWAxMZBz6jZAaRTUYTRMakJln3VdAeUju6E6tFn2I9feY5wtGatTm2KIgXoXYFZB0pTPQt2Oj0sNaRuX3AZDZD}&{object=http://www.google.com}&https://graph.facebook.com/100002097766610/og.likes"];
NSURL *url = [NSURL URLWithString: stringurl];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url];
[request1 setURL:url];
[request1 setHTTPMethod:#"POST"];
[request1 setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&response error:&error];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string..:%#",string);
But I am getting empty string. May be I am making wrong url string. If any one know that how to make the curl post request. Please give me some idea.
Thanks to all.
I attached some codes below:
Body data of Http POST request should located in 'Body', So I used 'setHttpBody:' method.
NSString *userId = #"Your ID Facebook ID";
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/og.likes", userId]];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url];
[request1 setURL:url];
[request1 setHTTPMethod:#"POST"];
NSString *body=[NSString stringWithFormat:#"access_token=YOUR_APP_ACCESS_TOKEN&object=OG_OBJECT_URL"];
[request1 setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&response error:&error];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string..:%#",string);

newby IOS: unable to redirect url

This is my first IOS project. Having a tough time getting login to work. The site has a meta_refresh to another url. I've tried to send another request to the url in the meta_refresh but then the app just hangs. I'm sure that I'm doing something wrong but I'm using XCode 4.4 so a lot of the NSURLConnection delegate methods have been deprecated.
Here's what I'm doing:
NSString *urlAsString = baseURL;
urlAsString = [urlAsString stringByAppendingString:#"?user[login]=username"];
urlAsString = [urlAsString stringByAppendingString:#"&user[password]=password"];
urlAsString = [urlAsString stringByAppendingString:#"&origin=splash"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"POST"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if([data length] > 0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
NSRange obj = [html rangeOfString:#"http-equiv=\"refresh\""];
NSInteger len = obj.length;
} else if([data length] == 0 && error == nil) {
NSLog(#"No data was returned.");
} else {
NSLog(#"Error happened = %#", error);
}
Here's what I'm getting:
Another question is that I've read that I should use asynchronous connection. The trouble is that I need the data scraped from the site to display on the screen. If I display the screen before the data is returned, then I won't have any data -- or am I not understanding how this works?
Thanks.
--Tony
I think that maybe you're a mixing stuff. You're setting a string url with GET values and then you set the HTTPMethod to POST and I don't know if that is going to work fine.
Here's a code that I have to send values with POST:
NSString *post = [NSString stringWithFormat:#"&user_login=%#&user_password=%#&origin=%#,username,password, splash];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:baseURL]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

Google Reader Token Request giving 403 error

I am trying to get the token from google reader for my iPhone project. I am able to get the Authorization but when I request for the token, I get a 403 Forbidden
Below is my code implementation. Any help would be appreciated.
//The tokenStorer contains the Authorization key
NSString *tokenStorer = [[NSUserDefaults standardUserDefaults]valueForKey:#"authKey"];
NSLog(#"%#", tokenStorer);
NSDictionary *cookieDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"www.google.com", #"Host",
#"iReader", #"User-Agent",
#"gzip, deflate", #"Accept-Encoding",
tokenStorer, #"Authorization",
nil
];
//#"Auth", NSHTTPCookieName, tokenStorer, NSHTTPCookieValue, #"./google.com", NSHTTPCookieDomain, #"/", NSHTTPCookiePath, nil];
//NSHTTPCookie *authCookie = [NSHTTPCookie cookieWithProperties:cookieDictionary];
//Google token url "http://www.google.com/reader/api/0/token?client=clientName"
NSURL *url=[[NSURL alloc] initWithString:GOOGLE_READER_TOKEN_URL];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:url];
[urlRequest setHTTPMethod:#"GET"];
[urlRequest setAllHTTPHeaderFields:cookieDictionary];
NSData *reciveData;
NSURLResponse *response;
NSError *error;
reciveData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSMutableURLRequest *tokenRequest= [[NSMutableURLRequest alloc] initWithURL:url];
NSString *trial = [[NSString alloc]initWithData:reciveData encoding:NSASCIIStringEncoding];
NSLog(#"%# %d",trial, response);
[url release];
The below code solved my problem:
-(id)queryLoginDetails {
//authKey returns the authorization key
NSString *tokenStorer = [[NSUserDefaults standardUserDefaults]valueForKey:#"authKey"];
NSLog(#"%#", tokenStorer);
NSString *auth = [[NSString alloc] initWithString:
[NSString stringWithFormat:#"GoogleLogin auth=%#", [tokenStorer substringToIndex:[tokenStorer length]-1]]];
NSDictionary *createHeader = [[NSDictionary dictionaryWithObjectsAndKeys:#"www.google.com", #"Host", #"iReader", #"User-Agent", #"gzip, deflate", #"Accept-Encoding", auth, #"Authorization", nil]retain];
NSURL *url =[NSURL URLWithString:GOOGLE_READER_TOKEN_URL];
NSData *recieveData;
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:url];
[urlRequest setHTTPMethod:#"GET"];
[urlRequest setAllHTTPHeaderFields:createHeader];
NSURLResponse *response;
NSError *error;
recieveData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSString *myString = [[NSString alloc]initWithData:recieveData encoding:NSASCIIStringEncoding];
return myString;
}

How to post a string to web server url in iphone sdk?

How can I post a string(i.e) a word to web server url in iphone sdk?
Some sample codes or tutorials would be appreciated.
Thanking you.
This may help you, although I havent tested it:
NSMutableString *httpBodyString;
NSURL *url;
NSMutableString *urlString;
httpBodyString=[[NSMutableString alloc] initWithString:#"Name=The Big Bopper&Subject=Hello Baby&MsgBody=...You knooow what I like...Chantilly lace..."];
urlString=[[NSMutableString alloc] initWithString:#"http://www.somedomain.com/contactform.php"];
url=[[NSURL alloc] initWithString:urlString];
[urlString release];
NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
[url release];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[httpBodyString dataUsingEncoding:NSISOLatin1StringEncoding]];
[httpBodyString release];
NSURLConnection *connectionResponse = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if (!connectionResponse)
{
NSLog(#"Failed to submit request");
}
else
{
NSLog(#"--------- Request submitted ---------");
NSLog(#"connection: %# method: %#, encoded body: %#, body: %a", connectionResponse, [urlRequest HTTPMethod], [urlRequest HTTPBody], httpBodyString);
NSLog(#"New connection retain count: %d", [connectionResponse retainCount]);
responseData=[[NSMutableData data] retain];
NSLog(#"response", responseData);
}
Source: http://www.iphonedevsdk.com/forum/iphone-sdk-development/6341-help-executing-http-url-post-variables.html
You can post the string to webservice in so many ways, In those one is
Using Rest protocol:
It has two sub types, HTTP GET, HTTP POST. The Http Get is simple.
You can add the value to the attribute and you can directly call the service.
Check the following code.
NSString *url = #"http://123.456.789.0?action=get_movies";
Here the I am passing the get_movies string to the server to the action attribute.
and then follow the code for requesting to server.
NSURL *reqUrl = [[NSURL alloc] initWithString:url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:reqUrl];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSStringEncoding responseEncoding = NSUTF8StringEncoding;
if ([response textEncodingName]) {
CFStringEncoding cfStringEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)[response textEncodingName]);
if (cfStringEncoding != kCFStringEncodingInvalidId) {
responseEncoding = CFStringConvertEncodingToNSStringEncoding(cfStringEncoding);
}
}
[reqUrl release];
NSString *dataString = [[NSString alloc] initWithData:data encoding:responseEncoding];
the dataString is the responseString from the server. You can use that.
Regards,
Satya.

iphone textview contents to url?

How can i have a uitextview value be taken and send to a predefined url using obj-c only without any html /php.
Take a look at NSURL. Use the text value of the UITextView as a parameter.
e.g.
NSURL *webURL = [NSURL URLWithString:MY_TEXTVIEW.text];
NSURLRequest *req = [NSURLRequest requestWithURL:webURL];
NSString *methodString = #"method";
NSString *parameterString = [NSString stringWithFormat:#"value=%#", textField.text];
NSString *apiRoot = #"http://www.domain.com";
NSURL *apiUrl = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#?%#", apiRoot,methodString,parameterString]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:apiUrl];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];