JSON to parse google translate API - ios

I am trying to parse data for google translate. In viewdidload, I wrote the following code.
NSString * target = #"ja";
NSString * source = #"en";
NSString *textEscaped = #"Hi, How are u";
NSString *ke=#"My_key";
NSString * urlText =[NSString
key=%#&source=%#&format=text&target=%#&q=%#",ke,source,target,textEscaped];
NSURL *url = [NSURL URLWithString:urlText];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response
error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",result);
I compared my code with different sources and my API is also activated but I am getting nothing in result string. Its bill. Why?

Create Your url like this:
[NSString stringWithFormat:#"https://www.googleapis.com/language/translate/v2key=%#&target=%#&q=%#",key, target, selectedWord];

Related

Why does my JSON post request end up as a hex value?

I'm trying to do a post from my iOS app. The JSON I'm trying to pass is called finalConvertedJson and when I print it on the log, it looks like a good JSON object.
But when I post it using the code below, the web service receives the code as a hex value and doesn't know how to handle it. When I try the same JSON object and URL in Postman, it works perfectly.
self.finalStringJson = [[NSString alloc] initWithData:self.finalConvertedJson encoding:NSUTF8StringEncoding];
NSLog(#"this this: %#", self.finalStringJson);
NSData* responseData = nil;
NSString *urlString = #"http://10.2.176.100:9000/TestIOS?mobileData";
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSString *bodydata=[NSString stringWithFormat:#"%#",self.finalConvertedJson];
[request setHTTPMethod:#"POST"];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPBody:req];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"the final output is:%#",responseString);
I'm guessing it's some sort of encoding issue in my iOS code.
I'm new to iOS so I may be missing something simple here.
I think the problem is on this line...
NSString *bodydata = [NSString stringWithFormat:#"%#",self.finalConvertedJson];
You are using self.finalConvertedJson but I think you intended to use self.finalStringJson. If so, you could just do this...
NSString *bodydata = self.finalStringJson;

GET request, iOS

I need to do this GET request:
http://api.testmy.co.il/api/sync?BID=1049&ClientCode=3847&Discount=2.34&Service=0&Items=[{"Name":"Tax","Price":"2.11","Quantity":"1","SerialID":"1","Remarks":"","Toppings":""}]&Payments=[]
In browser I get this response:
{
"Success": true,
"Atava": [],
"Pending": [],
"CallWaiter": false
}
But in iOS its not working.
I try:
NSString *requestedURL=[NSString stringWithFormat:#"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{\"Name\":\"Tax\",\"Price\":\"2.11\",\"Quantity\":\"1\",\"SerialID\":\"1\",\"Remarks\":\"\",\"Toppings\":\"\"}]&Payments=[]",BID,num];
NSURL *url = [NSURL URLWithString:requestedURL];
NSURLResponse *response;
NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[GETReply bytes] length:[GETReply length] encoding: NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
OR
NSString *requestedURL = [NSString stringWithFormat:#"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{'Name':'Tax','Price':'2.11','Quantity':'1','SerialID':'1','Remarks':'','Toppings':''}]&Payments=[]", BID, num];
OR
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:#"Tax" forKey:#"Name"];
[params setObject:#"2.11" forKey:#"Price"];
[params setObject:#"1" forKey:#"Quantity"];
[params setObject:#"1" forKey:#"SerialID"];
[params setObject:#"" forKey:#"Remarks"];
[params setObject:#"" forKey:#"Toppings"];
NSData *jsonData = nil;
NSString *jsonString = nil;
if([NSJSONSerialization isValidJSONObject:params])
{
jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
}
NSString *get = [NSString stringWithFormat:#"&Items=%#", jsonString];
NSData *getData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"GET"];
[request setTimeoutInterval:8];
[request setHTTPBody:getData];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
I tried all above code but it doesn't work(long time out.. just stuck on this).How to fixing this?
This is because your URL is not correct, this string should add percent escape. Try with this:
NSString *requestedURL=[NSString stringWithFormat:#"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{'Name':'Tax','Price':'2.11','Quantity':'1','SerialID':'1','Remarks':'','Toppings':''}]&Payments=[]",BID,num];
NSURL *url = [NSURL URLWithString:[requestedURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//and you use this url
// Send a synchronous request
NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"enter your url here"]];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if (error == nil)
{
// Parse data here
}
The NSURLResponse and NSError vars are passed into the sendSynchronousReqeust method so when it returns, they will be populated with the raw response and error (if any). If you need to check for stuff like response codes you can do so via the “response” variable you pass.

GET Request uses too many parameters- iOS

I'm trying to load a URL in NSMutableURLRequest for a GET request as below:
NSString *serverAddress = [NSString stringWithFormat:#"http://test.us.to:8080/api/offers?altId=%#&provider=%#&otherId=%#&tenantId=%#&createdAt=%#&otherOfferId=%#&postId=%#&pageId=%#&sourceUrl=%#&name=%#&description=%#&text=%#&category=%#&caption=%#&startTime=%#&expirationTime=%#&minPurchase=%#&numPurchases=%#&value=%#&percent=%#&count=%#&currency=%#&terms=%#&campaignId=%#&partnerId=%#&tenantIdAtPartner=%#&issuerName=%#&claimLimit=%#&onePerUser=%#&emailTemplateFile=%#",#"test",#"Facebook",#"",#"test",#"null",#"test",#"",#"",#"http://test.us.to/offers/harvester_summer13.html",#"Harvester",#"Harvester 2for1 TakeAway",#"Enjoy!",#"voucher",#"Harvester 2for1 TakeAway",[NSNumber numberWithInt:0],#"test",[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],#"1000",[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],#"GBP",#"",[NSNumber numberWithInt:1259],#"null" ,#"null" ,#"null",[NSNumber numberWithInt:100],[NSNumber numberWithBool:false],#"templates/test.vm"];
NSURL *url = [NSURL URLWithString:[serverAddress urlEncodeUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:15.0];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"testuser", #"testpwd"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod: #"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"output data %#",response1);
I guess I'm loading way too many parameters using the url string. Is there a better way to pass parameters for a GET request ? The current output is null for response1
It looks to me like the issue is that you are encoding the whole url with some sort of encoding method, but you really just need to encode each parameter separately if it contains certain characters. For example:
NSString *serverAddress = #"http://test.us.to:8080/api/offers";
NSString *altIdParameter = [#"Escape?This?String?" urlEncodeUsingEncoding:NSUTF8StringEncoding];
NSString *aUrlParameter = [#"http://test.us.to/offers/harvester_summer13.html" urlEncodeUsingEncoding:NSUTF8StringEncoding];
NSString *getRequestUrl = [NSString stringWithFormat:%#?altId=%#&urlParam=%#", serverAddress, altIdParameter, aUrlParameter];
NSURL *url = [NSURL URLWithString:getRequestUrl];

How to reach members of json with iOS

I want to reach from ios to a .net .asmx web service, and I reach with the following code:
NSString *urlString = #"http://www.****.com/Mobile.asmx/HelloWorld";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
//...do something with the returned value
}
It returns clean json {"hellom":"Hello World","hellom2":"HelloWorld2"} but I can't reach members and value one by one
How can I do that?
You can convert JSON data into an object by using the following code...
NSData *jsonData = ... the data you got from the server
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
object will then be a NSDictionary like this...
#{
hellom : #"Hello World",
hellom2: #"HelloWorld2"
}
You can then get to the keys and values like any other dictionary.

MatrixDistance API from Google for iOS

I am trying to build an app with a map in which the user would select his origin address and destination address.. It all works fine, but I can't access the Google API Distance Matrix..
I am try with following:
NSString *urlPath = [NSString stringWithFormat:#"/maps/api/distancematrix/xml?origins=%#=%#&mode=driving&language=en-EN&sensor=false" ,polazisteField.text , odredisteField.text];
NSURL *url = [[NSURL alloc]initWithScheme:#"http" host:#"maps.googleapis.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:NSASCIIStringEncoding];
address.text = result;
, but have no luck, any idea how to resolve this?
I think your call has been considred as invalid API call.
try below code that is edited from your code snippet.
NSString *urlPath = [NSString stringWithFormat:#"/maps/api/distancematrix/json?origins=%#&destinations=%#&mode=driving&language=en-EN&sensor=false" ,polazisteField.text , odredisteField.text];
NSURL *url = [[NSURL alloc]initWithScheme:#"http" host:#"maps.googleapis.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];
NSMutableDictionary *jsonDict= (NSMutableDictionary*)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableDictionary *newdict=[jsonDict valueForKey:#"rows"];
NSArray *elementsArr=[newdict valueForKey:#"elements"];
NSArray *arr=[elementsArr objectAtIndex:0];
NSDictionary *dict=[arr objectAtIndex:0];
NSMutableDictionary *distanceDict=[dict valueForKey:#"distance"];
NSLog(#"distance:%#",[distanceDict valueForKey:#"text"]);
NSString *result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
address.text = [distanceDict valueForKey:#"text"];

Resources