0

I'm currently populating a UITableView with JSON data (NSArray format) from a remote webservice. I would like to speed up the application by making a call to the webservice and storing the JSON data to a local file.

also, is this a good way to do this so the user doesn't have to keep downloading data all the time?

What I'm stuck on is how to save the remote JSON file to a local file. In my -(void)saveJsonWithData:(NSData *)data method how do I save the remote data.

Here's the code I'm using so far (from some Stackoverflow searching)

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

Then call the function as

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

    [self saveJsonWithData:data];
}

thanks for help

user2588945
  • 1,681
  • 6
  • 25
  • 38

2 Answers2

1

On iOS you should be using NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) to get the document directory. There is no user directory.

Wain
  • 118,658
  • 15
  • 128
  • 151
0

Let iOS do the JSON parsing, then write it to a plain textfile through an outputstream

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];
}
Thomas Keuleers
  • 6,075
  • 2
  • 32
  • 35