2012-02-25 41 views
3

我正在接收JSON响应,并且能够使用我的应用程序中的数据。如何将JSON响应保存到可从UIWebWiew中加载的本地HTML文件中访问的文件

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

我一个UIWebView的HTML文件输入到使用“创建文件夹参考”选项和路径,以我的JS文件我的Xcode项目是html->js->app.js

我想保存响应为data.json某处在设备上,然后参考我的js文件,像这样request.open('GET', 'file-path-to-saved-json.data-file', false);

我该如何做到这一点?

回答

8

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

当应用程序安装时,我将包中的默认数据文件复制到Documents文件夹。当应用程序运行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 ]; 

要引用JSON文件在我的JS代码,我增加了一个URL参数“SRC”,并通过文件路径到应用程序文件夹。

request.open('GET', src, false); 
相关问题