How to save a JSON response to a file that will be accessible from a local HTML file loaded inside UIWebWiew

I get a JSON response and can use the data in my application.

I would like to save this answer in a file so that I can reference in a JS file located inside my project. I already requested this data once when the application starts, so why not save it in a file and not reference it, so only one call is required for the data.

HTML files for my UIWebView are imported into my Xcode project using the "create folder reference" option, and the path to my JS file is html->js->app.js

I want to save the response as data.json somewhere on the device, and then the link inside my js file, like this request.open('GET', 'file-path-to-saved-json.data-file', false);

How can i achieve this?

+3
source share
1 answer

After working with the idea, there’s something else that I came up with.

When the application is installed, the package has a default data file that I copy to the Documents folder. When the didFinishLaunchingWithOptions application didFinishLaunchingWithOptions , I call the following method:

 - (void)writeJsonToFile { //applications Documents dirctory path NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; //live json data url NSString *stringURL = @"http://path-to-live-file.json"; NSURL *url = [NSURL URLWithString:stringURL]; NSData *urlData = [NSData dataWithContentsOfURL:url]; //attempt to download live data if (urlData) { NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"data.json"]; [urlData writeToFile:filePath atomically:YES]; } //copy data from initial package into the applications Documents folder else { //file to write to NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"data.json"]; //file to copy from NSString *json = [ [NSBundle mainBundle] pathForResource:@"data" ofType:@"json" inDirectory:@"html/data" ]; NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil]; //write file to device [jsonData writeToFile:filePath atomically:YES]; } } 

Then, throughout the application, when I need to reference the data, I use the saved file.

 //application Documents dirctory path NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSError *jsonError = nil; NSString *jsonFilePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"data.json"]; NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath options:kNilOptions error:&jsonError ]; 

To reference the json file in my JS code, I added the URL parameter for "src" and passed the path to the Applications folder.

  request.open('GET', src, false); 
+8
source

Source: https://habr.com/ru/post/974924/


All Articles