Question

I need to make an offline browser on my iOS application, which allows the following:

When you have an internet connection (wifi, 3g, 4g, ...) you can download all the web pages you need to read during the day, then you can browse the content also when you have no internet connection. I import the data from JSON file.

How can I do this?

Was it helpful?

Solution

If you have the data downloaded, save it to the documents directory and check if no internet connection, then load the content from the documents directory.

Get Documentpath

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];

If you have an NSDictionary:

NSString *path = [NSString stringWithFormat:@"%@",[paths objectAtIndex:0]];
NSDictionary *dict = [[NSDictionary alloc] init];
[dict writeToFile:[path stringByAppendingPathComponent:@"myOfflineData"] atomically:NO];

And to get it:

NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:[path stringByAppendingPathComponent:@"myOfflineData"]];

Or save it with a NSString etc.

To catch up your Example:

NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http:......."]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil]; jsonResults = [jsonObjects objectForKey:@"nodes"];
[jsonData writeToFile:[path stringByAppendingPathComponent:@"myOfflineData"] atomically:NO];

And if you are offline:

NSData *jsonData = [[NSData alloc] initWithContentsOfFile:[path stringByAppendingPathComponent:@"myOfflineData"]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top