0

現在、リモート Web サービスからの JSON データ (NSArray 形式) を UITableView に入力しています。Web サービスを呼び出し、JSON データをローカル ファイルに保存することで、アプリケーションを高速化したいと考えています。

また、これは、ユーザーが常にデータをダウンロードし続ける必要がないようにするための良い方法ですか?

私が行き詰まっているのは、リモート JSON ファイルをローカル ファイルに保存する方法です。私の-(void)saveJsonWithData:(NSData *)data方法では、リモートデータをどのように保存しますか。

これまでに使用したコードは次のとおりです(いくつかのStackoverflow検索から)

-(void)saveJsonWithData:(NSData *)data{

 NSString *jsonPath=[[NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:@"/data.json"];

 [data writeToFile:jsonPath atomically:YES];

}

-(NSData *)getSavedJsonData{
    NSString *jsonPath=[[NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:@"/data.json"];

    return [NSData dataWithContentsOfFile:jsonPath]
}

次に、関数を次のように呼び出します

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    [self saveJsonWithData:data];
}

手伝ってくれてありがとう

4

2 に答える 2

1

iOSNSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)では、ドキュメント ディレクトリを取得するために使用する必要があります。ユーザーディレクトリはありません。

于 2013-09-05T09:29:28.290 に答える
0

iOS に JSON 解析を実行させ、出力ストリームを介してプレーン テキスト ファイルに書き込みます。

NSData *jsonData = yourData;
NSError *error;

// array of dictionary
NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];

if (error) {
    NSLog(@"Error: %@", error.localizedDescription);
} else {
    NSArray *documentsSearchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [documentsSearchPaths count] == 0 ? nil : [documentsSearchPaths objectAtIndex:0];

    NSString *fileName = @"file.json";

    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

    NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];
    [outputStream open];

    [NSJSONSerialization writeJSONObject:array
                                toStream:outputStream
                                 options:kNilOptions
                                   error:&error];
    [outputStream close];
}
于 2013-09-05T09:51:34.073 に答える