2012-02-25 14 views
3

私はJSON応答を受け取っており、アプリケーション内のデータを利用できるようになっています。UIWebWiew内にロードされたローカルHTMLファイルからアクセスできるファイルにJSON応答を保存するにはどうすればいいですか?

この応答をファイルに保存して、プロジェクト内のJSファイル内で参照できるようにしたいとします。私は、アプリケーションが起動されたときにこのデータを一度要求しています。なぜなら、ファイルに保存してその間データを参照する必要がないからです。私のUIWebViewのため

HTMLファイルは、私は、デバイス上のdata.jsonどこかのように応答を保存する「フォルダの参照を作成」オプションと私のJSファイルへのパスがhtml->js->app.js

で使用して私のXcodeプロジェクトにインポートされており、このような私のjsファイル内の参照request.open('GET', 'file-path-to-saved-json.data-file', false);

どうすればいいですか?

答えて

8

アイデアを参考にした後、私が思いついたことがもう少しあります。

アプリケーションがインストールされると、ドキュメントフォルダにコピーする既定のデータファイルがパッケージにあります。アプリケーション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パラメータを追加し、ファイルパスをアプリケーションドキュメントフォルダに渡しました。

request.open('GET', src, false); 
関連する問題