Created
July 17, 2014 12:45
-
-
Save lumaxis/a5a72af577a7a4849442 to your computer and use it in GitHub Desktop.
iOS: Write a Foundation object as JSON file to disk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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