My iOS app is getting the code inside (ex. 101), and by that code it reads JSON file (ex. 101.json) on server and read the data inside. Everything is working good, but how to do that if there's no file (for that code) on server (now it's just showing no data if file not found) and if there's no internet connection just to get data from JSON file inside the app? Here's my code:
NSString *baseURLStr = @"http://myserverurl/";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:[baseURLStr stringByAppendingFormat:@"%d/%d.json", int1, int2]]];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
I found out how to read the file inside the app if there's no internet connection.
if (data == nil){
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"FAILED" ofType:@"json"]];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
self.members = json[@"data"];
}
else {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
self.members = json[@"data"];
}
There are three types of issues you might want to check for:
Connection errors: Check to make sure the connection didn't fail; if it did fail, the data will be
nil
and theNSError
object would be populated; typical causes would be an invalid server name in the URL, server was down, or no internet connection at all);HTTP errors: If doing a HTTP request, you want to check that the web server reported success retrieving the page/resource, namely that you received HTTP status code of 200; an example of an error condition might be a 404 - not found error (see the HTTP Status Code Definitions for more complete list); and
Server code errors: Check to make sure the server responded with valid JSON, i.e. check to see if the response received can be parsed as JSON successfully (you want to make sure there was no problem in the server code that generated the JSON, e.g. a mistake in your server code).
Thus:
Obviously, if it was NSArray, change that above
JSONObjectWithData
line to return array, but the concept is the same.Or, better, use asynchronous connection (as you should never use synchronous connections on the main queue):
For checking the Internet Connection available or Not, There are many of resources you will get for this. I usually use the reachebility