JSON answer to check if a server is reachable - iphone

I have an app that just opened call a webserver page that gives me a json string.
When I'm on the local network all works without problem but when I open the app outside the local network and without vpn the app crashes.
How can I control the json string?
This is my code:
NSString *urlstr = [[NSString alloc] initWithFormat:#"%#yes.php", av];
NSURL *url = [[NSURL alloc] initWithString:urlstr];
NSError* error = nil;
NSString* urlString = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSString *newStr;
NSData* data=[newStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
sn1 = [[json objectForKey:#"Rele1"] intValue];
I want to compare the json answer with a NULL value, if the two parameters are equal I show an alert.
EDIT: If I try to read any value, the app crashes waiting the json reply...
I have bypassed the problem with an NSURLRequest with the timeoutInterval parameter that closes the connection after n seconds.

Amongst other things, you fail to:
check whether the attempt to fetch an ASCII-encoded string from a remote URL failed (obvious possibilities: the URL is unreachable, the result is UTF-8 rather than ASCII);
check whether the JSON parsing succeeds (obvious possibility: the server 404d and returned an HTML error page instead)
check whether the returned JSON object was actually a dictionary (eg, it could be an array, in which case calling objectForKey: on it will raise an exception)
The parsing of return data as ASCII then re-encoding into UTF-8 is also probably redundant — because the one supersets the other it has the effect of a threshold test, otherwise preventing acceptable results from proceeding.

Does this code ever worked?
You should check error after [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
you are reading URL data into urlString but then get NSData from uninitialized newStr and parse it?
again you should always check error whenever you provide it before anything else
why do you read the data as ASCII but the NSData as UTF8?

Related

Latin characters display ? objective-c

I am making a call to get a JSON response like this:
NSData *urlData=[NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&httpResponse error:nil ];
NSString *returnString=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
However, when I print the string using NSLog:
Emiratos �rabes Unidos
When I convert it to NSData like this:
NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
NSArray * response = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
It turns it to be (when I retrieve the value from the array):
Emiratos \Ufffdrabes Unidos
And when I put it in a label it displays it like this:
Emiratos �rabes Unidos
I would like to display in a label like this:
Emiratos Árabes Unidos
How can I do it?
The problem seems to be this line:
NSString *returnString =
[[NSString alloc] initWithData:urlData
encoding:NSUTF8StringEncoding];
You are assuming that the data is a string encoded as UTF8. But apparently it isn't. Therefore you're seeing the "replacement character" (codepoint U+FFFD) at this point.
You'll need to find out what encoding is actually being used. You can probably just experiment with other encodings. Alternatively, use NSLog to look at the data; an NSData object is logged as a sequence of hex bytes, so by looking at the bytes in that position, and by looking up various encodings on the Internet, you may be able to deduce what encoding is being used here.
(But if you use NSLog and you actually see FFFD at this point, then you've had it; the server itself is supplying the bad data and there's nothing you can do about it, as the good data is lost before you can get at it.)

ios - NSString losing content when used in NSUrl

I have the following code - note it has to objects with temp, but I will explain.
NSString *temp = _passedOnURL;
NSString *temp = #"http://google.com"; //I comment the one out that I do not use.
NSLog(#"TEMP - %#", temp);
NSURL *feedURL = [NSURL URLWithString:temp];
NSLog(#"FEED URL - %#", feedURL);
The _passedOnURL is a string with the contents passed from a Segue.
Now when I use the 1st temp, the FEED URL returns (null), but when I Log Temp it is still there, so somehow the NSURL does not read the string.
When I hardcode the string with the second temp - there is no issue.
In my mind there is no difference for the NSURL when it is reading the NSString yet, it seems to behave different.
Is there any reason for this??
EDIT
When I do the following code I have no issues:
_passedOnURL = #"http://www.google.com";
so I really have no explanation for this???
try escaping it : [NSURL URLWithString: [temp stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding]]
It seems you have an invalid url string stored in temp. Not every string can be converted to a url but the valid url. Invalid chars and format will lead a nil object after +URLWithString:. So would you let us know what is stored in temp when you try this?
According to the doc for URLWithString:
Parameters
URLString
The string with which to initialize the NSURL object. Must be a URL
that conforms to RFC 2396. This method parses URLString according to
RFCs 1738 and 1808.
Return Value
An NSURL object initialized with URLString. If the string was
malformed, returns nil.
So my guess is that your _passedOnURL is not a valid URL.
I would do a NSLog on your _passedOnURL to check if you are getting the string correctly from the other segue.

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];

Sending string via ftp : getting error

I'm trying to send a string via ftp using the code below but I'm getting an error:
{
//miscellaneous lines of code.....
//Convert contents of shopping cart into a property list
[Cart serializeCart];
//now need to transport the propertyList to the webserver
//first step is get the serialized propertylist from the documents folder
NSString *pathToSerializedCart = [rootPath stringByAppendingPathComponent:#"serializedCart.plist"];
NSString *shoppingCartString;
if (![fileManager fileExistsAtPath:pathToSerializedCart])
{
NSLog(#"ERROR:\nCouldnt find serialized cart in documents folder.");
}
else
{
NSData *serializedData = [NSData dataWithContentsOfFile:pathToSerializedCart];
shoppingCartString = [[NSString alloc] initWithData:serializedData encoding:NSUTF8StringEncoding];
}
NSLog(#"%#", shoppingCartString);
//Now that the cart is converted into a string. it is ready for transport
NSURL *url = [NSURL URLWithString:#"ftp://username:password#domainName.com/folder/serializedCart.xml"];
BOOL OK =[shoppingCartString writeToURL:url atomically:NO encoding:NSUTF8StringEncoding error:&error];
if(!OK) {
NSLog(#"Error writing to file %# , error = %#", url, [error localizedFailureReason]);
}
I'm getting the following console output for this code:
Error writing to file ftp://username:password#domainName.com/folder/serializedCart.xml , error = (null)
One of the variables: _domain in this error object in the last line when, I mouse over it during debugging says NSCocoaErrorDomain
I'm not sure how to debug this.
Could someone give any suggestions?
The writeToURL:.. methods don't support the FTP protocol. You'll have to use other mechanisms to write the string content onto an ftp server. You can look at tools such as ios-ftp-server to handle such uploads. You can also look at this sample code from Apple.

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.