Skip to content

Instantly share code, notes, and snippets.

@lumaxis
Created July 17, 2014 12:45
Show Gist options
  • Save lumaxis/a5a72af577a7a4849442 to your computer and use it in GitHub Desktop.
Save lumaxis/a5a72af577a7a4849442 to your computer and use it in GitHub Desktop.
iOS: Write a Foundation object as JSON file to disk
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:yourObject
options:(NSJSONWritingOptions) NSJSONWritingPrettyPrinted
error:&error];
NSString *jsonString;
if (! jsonData) {
NSLog(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription);
jsonString = @"[]";
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"data.json"];
[jsonString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(@"writing error: %@", error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment