2

Right now I have an app that successfully parses JSON from my website. So whenever there is no internet connection, my app crashes. Now I am trying to make it so that when the app is loaded with no internet connection, it will show the data that was shown previously. What would be the best way to do this?

I read this article but I don't know how to embed a JSON file into my app bundle. Could someone explain how to do this?

Thanks in advance!

Community
  • 1
  • 1
Alex Hamilton
  • 77
  • 3
  • 9
  • How much is the data?If it is not much use plist. if the size of data is more then introduce CoreData to your application. – Puneet Sharma Sep 10 '13 at 08:16

3 Answers3

1

The best way is:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"YourParsedJSON.plist"];

NSFileManager *fileManager = [NSFileManager defaultManager];

if (noInternet){
   if ([fileManager fileExistsAtPath: path]){

   // if this is true, you have a saved version of your JSON
         YourArray = [[NSMutableArray alloc] initWithContentsOfFile: path];
         // or
         YourDict = [[NSMutableArray alloc] initWithContentsOfFile: path];
   }
   else{
    // first time the app is running, and no internet, no json, inform user about this

    }

}
else{
    // make an array or dictionary ( what is your JSON )
        // response can be a NSDictionary or NSArray
        // YourArray = parsedJSON  or YourDict = parsedJSON

        [YourArray writeToFile:path atomically:YES];
        //or
        [YourDictionary writeToFile:path atomically:YES];
    }

I hope it helps !

incmiko
  • 3,922
  • 1
  • 20
  • 41
1

Use Apple Reachability sample code to check if your app is able to establish connection to your server.

On first successful request-response, parse the JSON and cache it to disk as a .plist file. This will save you parsing the stored response again. A parsed JSON response can be a NSDictionary or NSArray. Use the writeToFile:atomically: API to write it to disk.

On subsequent request, if reachability fails, i.e. no network connectivity, read the cached response from disk. You need to decide the cache duration and update the plist when a fresh response is fetched.

Hope that helps!

Community
  • 1
  • 1
Amar
  • 13,103
  • 7
  • 50
  • 69
0

EDIT:

I think I did not understand the question completely. Thanks Xman, for pointing it out. What I would have done in this case is - save the last loaded JSON file to my bundle and use it for displaying information while querying the server and loading updates in the background.

The flow should be like this:

  1. Parse and display data using local JSON file. (Assuming there is local copy of JSON file)
  2. Query the server for latest data.
  3. Upon receiving response, update the bundle with the latest JSON file.
  4. Then, do step 1. In case there is no JSON file, just start from step 2. If there is a Network error display the appropriate information.

This SO question answers how to handle Network connections in iOS: How to check for an active Internet connection on iOS or OSX?

Saving file locally: Assuming you have the unparsed JSON data in a NSString (responseString) do the following:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"latest_json.json"];

NSError *error;
[jsonString_ writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@", error)

Reading file

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"latest_json.json"];
NSString *jsonString_ = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];

Previous Answer

Embedding JSON file is similar to embedding any resource into your project. The following method shows you how I added an XML file and accessed it in my app.

Drag and drop your JSON/XML file to your resources group/folder in your XCode window. If you don't have the Resouces folder, it is better you create it. Then in your code do this:

NSString* filePath_ = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"json"];
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error: NULL];

the variable jsonstring contails the JSON information. It is upto you how you would like to parse it.

Community
  • 1
  • 1
Naz Mir
  • 1,028
  • 1
  • 9
  • 19
  • wrong solution...he cant add JSON file by dragging and dropping..he is downloading it from internet, now he need to save the last accessed JSON data and use it when not connected to internet...! – Prashant Nikam Sep 10 '13 at 08:32
  • Why do you suggest loading JSON to NSString? That does not end up as useful, because NSJSONSerialisation that should convert your JSON into NSDictionary/NSArray takes NSData for input. – igraczech Jul 17 '14 at 13:14