2012-02-25 43 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); 
相關問題