Fetch XML of Distance Matrix API (google) on iPhone - iphone

I'm trying to fetch the XML data from a query to the api without success...
I'm doing this:
[...]
NSURL *googleAPIurl = [NSURL URLWithString:#"http://maps.googleapis.com/maps/api/distancematrix/xml?origins=28.124822,-15.430006&destinations=28.126953,-15.429874|28.072056,-15.416574|28.103186,-15.417665|28.127916,-15.625403|28.099125,-15.418365|28.107740,-15.454050|28.050825,-15.454066|28.051640,-15.454104|28.101788,-15.423592|28.113750,-15.446980|28.098871,-15.420730|28.098217,-15.449371|28.083364,-15.418172&mode=driving&sensor=false"];
NSData *xmlData = [NSData dataWithContentsOfURL:googleAPIurl];
NSError *error;
GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
if (xmlDocument == nil)
{
NSLog(#"NIL XML");
}
[...]
I'm ALWAYS getting a nil XML. NSData is always nil. I don't know what is happening with this. If I use a url with one destination only it works, but not for more than one. Also, I'm using the same method to retrieve xml with google places api with no problems. This is driving me crazy...
Please point me in the right direction.
Thanks in advance.

I suggested replacing all of the '|' with '%7C'
Turns out this is the more proper method to cover all of these character encoding issues:
NSURL *googleAPIurl = [NSURL URLWithString:[distancesURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Related

parsing json - reached max depth

I want to parse the comments of a reddit post with over 500 comments.
For example this one: http://www.reddit.com/comments/xu11o
The json url is: http://www.reddit.com/comments/xu11o.json
In am using SBJson to achieve this.
When I try to get a NSArray with this code:
NSString* response = [request responseString];
NSArray* responseArray = [response JSONValue];
I get this error message: -JSONValue failed. Error is: Input depth exceeds max depth of 32
Changing the depth to a higher number of for example 100 makes my app crash.
If the reddit post has only 20 comments I get the NSArray and can successfully display them.
What do I have to change to get the NSArray?
Have you tried Apple's NSJSONSerialization JSON parsing library? It works.
NSString *urlString = #"http://www.reddit.com/comments/xu11o.json";
NSURL *url = [NSURL URLWithString:urlString];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:
[NSURLRequest requestWithURL:url]
returningResponse:&response
error:&error];
id jsonObj = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
// Do something with jsonObj which is an array.
Just make sure you switch your download code to asynchronous before shipping.
Best regards.
Try my JSON parser library, it has no such limitation:
http://github.com/H2CO3/CarbonateJSON
This "limitation" of SBJsonParser is a security feature, protecting you from presumed malicious JSON. The limit is configurable through the maxDepth property. The default is 32, as you've found. You can change it to any integer value you want, or turn the max depth check off by setting it to 0.
I had the same issue with sbjson. Changing the maxDepth (SBJsonParser.m)to 128 solved the problem.

JSON returning null

I'm having a bit of trouble parsing some returned JSON. I'm fairly new to working with JSON. I'm trying to get the company name from the first JSON array element. I have a feeling that I'm confusing the use of NSMutabeArray and NSMutableDictionary. What I get is null. Any idea what I'm doing wrong?
NSString *url = #"http://www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG,AAPL";
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: url]];
//parse out the json data
NSError* error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:data //1
options:kNilOptions
error:&error];
NSString* companyName = [[json objectAtIndex:0] objectForKey:#"name"] ; //Where I need some help
NSLog(#"we got %#", companyName);
Load that url in your browser. Looks like google is prefixing the JSON with //. I think NSJSONSerialization is tripping on that. Try this
NSRange range = NSMakeRange(2, [data length] - 3);
NSData *noPrefix = [data subdataWithRange:range];
Then send that to the parser.
You put in an error object, but you never looked at it. If you had, you would see that the data is corrupted:
Error Domain = NSCocoaErrorDomain Code = 3840 "The data couldn’t be read because it has been corrupted." (Invalid value around character 1.) UserInfo = 0x10030a8f0 { NSDebugDescription = Invalid value around character 1. }
I changed the value of the options parameter to see this error. I have
NSMutableArray* json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers |NSJSONReadingAllowFragments error:&error];

Removing // from NSMutableArray

When I NSLog the contents of an NSMutableArray I get null. I believe I know what the issue is.
I'm having a bit of trouble trying to figure out how to remove "//" at the beginning of this JSON output. If you load http://www.google.com/finance/info?infotype=infoquoteall&q=AAPL,C into your browser you'll see the "//" at the beginning. I believe that the "//" is what is causing the array to return null. How could I go about removing the two dashes? Below is I have what I've done thus far...
NSString *url = #"http://www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG,AAPL";
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: url]];
//parse out the json data
NSError* error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:data //1
options:kNilOptions
error:&error];
NSLog(#"json is %#", json); //returns "json is (null)"
You can try this:
NSData *newData = [data subdataWithRange:NSMakeRange(4, [data length] -4)];
This gets rid of the first four characters. There was a control character the two slashes and a space before the first "[", and this gets rid of those. I tried this but the data still had a flaw in it further on.

Not able to create valid nsurl

I am trying to parse data from a xml web service but I am not able to get my url. Please check my code:
NSLog(#"log url: %#",url);
[url stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];
NSLog(#"%#",url);
[url stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSLog(#"%#",url);
NSURL *URL = [NSURL URLWithString:url];
NSXMLParser *home_Parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
[home_Parser setDelegate:self];
[home_Parser parse];
[home_Parser release];
I am always getting URL as nil. The reason is my string url has space included. I have tried to replace it and escape it but it is not working. Following is the url that I am using
http://www.mydomain.com/radioListGenre.php?genre=Radiostations playing Rock
how can I remove this space. Is there any other technique the those I used above.
Thanks
Pankaj
stringByAddingPercentEscapesUsingEncoding and stringByReplacingOccurrencesOfString operate on the string provided and return a string. You're not assigning the return value to anything so url isn't changing, the return value is just vanishing into space. You want something more like:
url = [url stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];
assuming url is a mutable string. Now url contains the modified version of url. Without the assignment it's effective the same as doing something like this:
a + 1;
instead of:
a = a + 1

Cannot read XML File

got a little problem with receiving the contents of a xml file (using TouchXML).
My first query works very well, looks something like this:
NSString *url = [NSString stringWithFormat:STATION_ID, latitude, longtitude];
CXMLDocument *rssParser = [[CXMLDocument alloc] initWithContentsOfURL:[NSURL URLWithString:url] options:0 error:nil];
NSLog(#"%#",rssParser);
so this log gives me the complete XML file.
after that, in another method im trying the same:
NSString *url = [NSString stringWithFormat:WEATHER_URL, [positionInformation objectForKey:#"stationId"]];
CXMLDocument *rssParser = [[CXMLDocument alloc] initWithContentsOfURL:[NSURL URLWithString:url] options:0 error:nil];
NSLog(#"%#", rssParser);
but the log im getting is (null).
Loggin the URL String gives me the right URL without spaces or something, the URL Log for example looks like this:
NSString *url = [NSString stringWithFormat:WEATHER_URL, [positionInformation objectForKey:#"stationId"]];
NSLog(#"%#", url);
The result in the debugger Console is
http://api.wunderground.com/weatherstation/WXCurrentObXML.asp?ID=KCASUNNY19
looking at this file with my browser seems to be ok. Anybody know whats going wrong?????
I also tried, first to get the content of this URL by stringWithContentsOfURL, but this also not worked.
This guy was having the same problem: http://www.iphonedevsdk.com/forum/iphone-sdk-development/15963-problem-initwithcontentsofurl.html. Looks like the API at Weather Underground is expecting a user-agent and returning a 500 HTTP response when it doesn't see one. You can use -initWithData:options:error: on CXMLDocument to pass the data you get using NSMutableURLRequest.
You should try using the error argument of initWithContentsOfURL:options:error:. Create an NSerror *object, and pass it in thusly:
NSError *error;
CXMLDocument *rssParser = [[CXMLDocument alloc] initWithContentsOfURL:[NSURL URLWithString:url] options:0 error: &error];
If you don't get an rssParser object, check that error.
i copied the content of this xml file to my own server and changed the url path.
this works correcty, so i think there is a problem with reading this ".asp" file.
hmm. but its XML content, strange.
//edit:
i made a little php file on my server that returns the content of the "asp" file:
<?php
echo file_get_contents("http://api.wunderground.com/weatherstation/WXCurrentObXML.asp?ID=KCASANFR70");
?>
reading the contents of my script works, but this workaround is not what i want.
oh damn =/
Are you sure that your URL string is properly encoded, so that the question mark gets interpreted as a query? You might want to look at using dataUsingEncoding or stringUsingEncoding on your URL before using it to initialize rssReader.