Diego Rodrigues
Diego Rodrigues

Reputation: 73

Save JSON Data In Cache

I am working on a project that has a TableView which loads the contents of a JSON file on my server. Everything works correctly, but I have two problems.

1) When I change the View and load a different View, when I came back to this TableView ... the TableView tries to re-load the contents, there is no errors, but the progress bar appears briefly. How to avoid this from happening?

2) My second problem is that, once loaded, if I lose the internet connection and change the View, the content gets lost. Even I already downloaded. How would I do the cache of this information?

Here is the code:

@interface ProgramacaoTableViewController ()
{
    // Object thats hold the content
    MProgramacao *_programacao;
}

    - (void)viewDidLoad
{
    [super viewDidLoad];

    // TS MESSAGE
    [TSMessage setDefaultViewController:self];
    [self.navigationController.navigationBar setTranslucent:YES];

    // Add Refresh Control
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];

    [refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refreshControl;

    ////
    // Check Connection and Load Data
    if ([self IsConnected]) {

        // YES INTERNET
        // show loader view
        [ProgressHUD show:@"Loading.."];

        // fetch the feed
        _programacao = [[MProgramacao alloc] initFromURLWithString:@"http://myurl..."
                                                        completion:^(JSONModel *model, JSONModelError *err) {

                                                            //hide the loader view
                                                            [ProgressHUD dismiss];

                                                            //json fetched
                                                            [self.tableView reloadData];

                                                        }];


    }
    else {
        // NO INTERNET
        [TSMessage showNotificationWithTitle:NSLocalizedString(@"Error Message", nil)
                                    subtitle:NSLocalizedString(@"try again", nil)
                                        type:TSMessageNotificationTypeError];

    }

}

I edit the code.

Upvotes: 0

Views: 664

Answers (1)

Matteo Gobbi
Matteo Gobbi

Reputation: 17687

You should download the data just in the viewDidLoad, and then when the user WANT, he can pull the tableView to refresh. This is the correct way.

In this way, your tableView will remains loaded also when you push a viewController and then come back, and your "temporary cache" is your array _programacao.

If you want store the data also in case you close the app, you could use for example CoreData, but this is another thing that is not necessary for your purpose.

Upvotes: 1

Related Questions