如何将JSON响应保存到可从UIWebWiew中加载的本地HTML文件中访问的文件

我收到了一个JSON响应,并且能够使用我的应用程序中的数据。

我想将这个响应保存到一个文件中,以便我可以在我的项目中的JS文件中引用。 当应用程序启动时,我已经请求了这个数据,所以为什么不把它保存到一个文件和引用中,因此只需要一个数据调用。

我的UIWebView的HTML文件被导入到我的Xcode项目中使用“创build文件夹引用”选项,我的JS文件的path是html->js->app.js

我想保存响应作为data.json设备上的某个地方,然后引用我的js文件,像这样request.open('GET', 'file-path-to-saved-json.data-file', false);

我怎样才能做到这一点?

在完成这个想法之后,我想到了更多。

当安装应用程序时,我将该文件夹中的默认数据文件复制到“文档”文件夹中。 当应用程序didFinishLaunchingWithOptions运行时,我调用以下方法:

 - (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]; } } 

然后在整个应用程序中,当我需要引用数据时,我使用保存的文件。

 //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 ]; 

为了引用我的JS代码中的json文件,我添加了“src”的URL参数,并将文件path传递给Applications Documents文件夹。

  request.open('GET', src, false);