Can't fetch data from NSURL - iphone

I am fetching result from google place search url, if I search for "Newyork", everything works fine. But if I give "New york", the result json is different and I can't take it in NSData.
This is the url I am using:
https://maps.googleapis.com/maps/api/place/textsearch/json?query=New york&sensor=true&key=MY_KEY
I am using below code to fetch the data:
NSURL *googleURL = [NSURL URLWithString:url]; //url is above url
NSURLResponse *response;
NSData *data;
NSError *error;
data = [NSURLConnection sendSynchronousRequest: [NSURLRequest
requestWithURL: googleURL] returningResponse: &response error: &error];
NSLog(#"data %#",data); // but I am getting null here
How to overcome this? Thanks in advance

Assuming that url is:
NSString *url = #"https://maps.googleapis.com/maps/api/place/textsearch/json?query=New york&sensor=true&key=MY_KEY";
Try using this:
NSURL *googleURL = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
This will format the string for URLs containing spaces. To confirm it is working, print it out to the console.
NSLog(#"URL with Percent Escapes: %#", [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
It should return something like this (I believe the percent escape for a space is %20).
URL with Percent Escapes: https://maps.googleapis.com/maps/api/place/textsearch/json?query=New%20york&sensor=true&key=MY_KEY

Related

NSJSONSerialization does not return data, but its showing data in json viewer

NSJSONSerialization returns null when i try to implement a particular api from the server, but other api's from the server works fine , when i tried the api in web it returns data of json type , and i have checked it in json viewer also , and it worked fine , NSData also returns some data, can Anyone help me get through it ?
NSString *urlString = #"url";
NSURL *url = [NSURL URLWithString:urlString];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:url];
_dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if(error != nil){
NSLog(#"JSON Error: %#", error);
return;
}
I have tried the above written code.
---Edited-----
Since it was a issue from server side as server was sending an Invalid Character along with response, In json validator it was passing but not in a actual Program , Hence closing the question.
The Problem is of Escape Sequences in your URL and you are not escaping them. You have to escape those sequences properly.
NSString *urlString = #"url";
NSString *encodedString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodedString];
Take a Look at Documentation.
Check also the Escape Sequences.
Try this :
NSString *urlString = #"url";
NSURL *myUrl = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Make a NSURLConnection and request the JSON with NSURLRequest because I don't think the 'json' is an actual file that has content so you could use dataWithContentsOfURL:

getting error during json parsing

I am getting error during json parsing. When I trying to send the parameters using browser then it send me the success message that record store successfully. But when I send form parameters through iphone then i get nothing and in array i get NULL value.This is the json parsing code.
NSString *string1 = [[NSString alloc]initWithFormat:#"http://195.78.76.34/bedspace/mobileapi.php?action=save_room_info&Area=%#&Address=%#&Living_room=%#&Amenties=%#&Type_of_cost=%#&cost_of_room=%#&Security_deposit=%#&STLC=%#&Days_available=%#&Bill_included=%#&Broadband_available=%#&Exc_Smoke=%#&Exc_gender=%#&Exc_pets=%#&Exc_age=%#&Exc_language=%#&Exc_nationality=%#&Exc_Sexorientition=%#&Exc_intrest=%#&Pre_smoke=%#&Pre_gender=%#&Pre_occupation=%#&Pre_pets=%#&Pre_min_age=%#&Pre_max_age=%#&Pre_nationaltiy=%#&Pre_Language=%#&Pre_Sexorientition=%#&Misc=%#&Title=%#&Description=%#&Your_name=%#&Your_email=%#&Email_alert=%#&No_of_rooms=%#&Country=%#&City=%#&State=%#&Size_of_property=%#&Type_of_property=%#&Occupets_property=%#&My_property_status=%#&Amenties_two=%#&Size_of_room=%#&Refrence_required=%#",area,address,livingRoomVal,amenties,typeOfCost,costOfRoom,securityDeposit,STLC,daysAvailable,billsIncluded,broadbandAvailable,eSmoke,eGender,ePets,eAge,eLanguage,eNationality,eSexOrientation,eInterest,pSmoke,pGender,pOccupation,pPets,pMinAge,pMaxAge,pNationality,pLanguage,pSexOrientation,misc,title,description,yourName,yourEmail,emailAlerts,noOfRooms,country,city,state,sizeOfProperty,typeOfProperty,occupentsOfProperty,myPropertyStatus,amentiesTwo,sizeOfRoom,refrenceRequired];
NSLog(#"string 1 value %#",string1);
NSURL *urlRequest = [NSURL URLWithString:string1];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:urlRequest];
NSData *dataResponce = [NSURLConnection sendSynchronousRequest:request returningResponse:Nil error:Nil];
NSError *jsonParsingError = nil;
NSArray *publicTimeline = [NSJSONSerialization JSONObjectWithData:dataResponce options:0 error:&jsonParsingError];
NSLog(#"get values %#",publicTimeline);
I don't know what the problem is. I also used SBJsonParser but i get nothing in array and after that I used NSJSONSerialization and same problem still happen i got nothing in NSData and in NSArray.
You cannot fill the URL with parameters and still expect it to be legal, so you need to URL Encode the URL before use:
NSURL *urlRequest = [NSURL URLWithString:[string1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Get content of webservice

I've got an URL like here. When I type that into Safari's address bar I see an result like "Error" or "OK".
So, how do I properly call that URL from within my code and get that result as a string?
I've tried it with NSURLConnection, NSURLRequest and NSURLResponse but my response object is always nil.
The "response" in those classes refers to the protocol response (HTTP headers, etc.), not the content.
To get the content, you have a few options:
Use NSURLConnection in asynchronous mode: Using NSURLConnection
Use NSURLConnection in synchronous mode:
// Error checks omitted
NSURL *URL = [NSURL URLwithString:#"http://www.myserver.com/myservice.php?param=foobar"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
Use [NSString stringWithContentsOfURL:]
NSURL *URL = [NSURL URLwithString:#"http://www.myserver.com/myservice.php?param=foobar"];
NSString *content = [NSString stringWithContentsOfURL:URL];
Of course, you should use options 2 and 3 only if your content will be really small in size, to maintain responsiveness.

Send http request with Chinese words

NSString *urlAddress = #"http://www.test.com/test.jsp?Query=哈囉";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
NSURLResponse* myURLResponse;
NSError* myError;
NSData* data = [NSURLConnection sendSynchronousRequest: requestObj returningResponse:&myURLResponse error:& myErr];
I want to use http get method to send request, but failed.
English alphabets work well.
I.e., I want to convert "哈囉" to "%E5%93%88%E5%9B%89" so that the response will successfully return. It seems not to be converted by itself automatically.
Anyone could help me solve this problem?
Thanks a lot!
urlAddress = [urlAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
(docs)

iPhone Google Maps KML Search

I'm using Google maps with KML Query. But my query string is "Japanese" string "マクドナルド"
I'm using http://maps.google.co.jp.
When requesting data, I'm getting "0" bytes. But the same query when I put in browser, its download a KML file. My code is as follows:
query = [NSString stringWithFormat:#"http://maps.google.co.jp/maps?&near=%f,%f&q=マクドナルド&output=kml&num=%d", lat,lon, num];
NSURL* url = [NSURL URLWithString:query];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSLog(#"Quering URL = %#", url);
NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] autorelease];
NSData *myData = [NSURLConnection sendSynchronousRequest:request returningResponse: &response error: nil ];
NSInteger errorcode = [response statusCode];
I'm receiving "myData" with 0 bytes. why?
You need to URLencode the japanese text. A browser usually automatically encodes text for you, but NSURL won't.
Try something like
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8 );