7

Here i am reading and writing a json file.

Reading is done correctly but while i am writing a file it doesn't write data in json file.

Here is my code.

//reading Json file....
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"bookmark" ofType:@"json"];

NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
NSArray *bookmarkJson=[NSJSONSerialization JSONObjectWithData:content options:0 error:nil];
//this contains array's of dictionary....
NSDictionary *newBookmark=@{@"index":@"1.1.1.1",@"text":@"Header",@"htmlpage":@"page_name"};

//take new array to add data with previous one
NSMutableArray *temp=[[NSMutableArray alloc]initWithArray:bookmarkJson];
// add object to new array...
[temp insertObject:newBookmark atIndex:0];

//now serialize temp data....
NSData *serialzedData=[NSJSONSerialization dataWithJSONObject:temp options:0 error:nil];

NSString *saveBookmark = [[NSString alloc] initWithBytes:[serialzedData bytes] length:[serialzedData length] encoding:NSUTF8StringEncoding];

//now i write json file.....    
[saveBookmark writeToFile:@"bookmark.json" atomically:YES encoding:NSUTF8StringEncoding error:nil];

In "saveBookmark" (NSString)object i got correct file format but in bookmark.json file i didn't got any new values.

Please help me with this......

mohammad sufyan
  • 73
  • 1
  • 1
  • 5
  • Can you do a NSLog and print out saveBookMark right before you save the file? What is the output? Is it as expected? – Gurtej Singh Aug 06 '15 at 10:17
  • Does the `error` parameter of `writeToFile:atomically:encoding:error:` say something? Does `saveBookMark` is correct before saving it? Could it be because you're using two different encoding (one for JSON, one for saving)? – Larme Aug 06 '15 at 10:18
  • 4
    From what I see, the `bookmark.json` in added as a resource in the project, and I don't think you can write to that file. You could move that file to the app's `Documents` folder. – Iulian Onofrei Aug 06 '15 at 10:21
  • Yes, Gurtej Singh , the saveBookmark is same as expected... – mohammad sufyan Aug 06 '15 at 10:35
  • May be yes, @Iulian Onofrei when i NSLog error this is the output: Error Domain=NSCocoaErrorDomain Code=513 "The operation couldn’t be completed. (Cocoa error 513.)" UserInfo=0x7fe7b1c9f600 {NSFilePath=bookmark.json, NSUserStringVariant=Folder, NSUnderlyingError=0x7fe7b1cebfb0 "The operation couldn’t be completed. Permission denied"} – mohammad sufyan Aug 06 '15 at 10:39
  • Please see answer below and if it helps you out. Thanks @Lulian for the edit and the right direction :) – Gurtej Singh Aug 06 '15 at 11:03
  • @GurtejSingh, It's `Iulian`, with capital `i`. – Iulian Onofrei Aug 06 '15 at 11:10
  • where should i put my "bookmark.json" file exactly in my App....? – mohammad sufyan Aug 06 '15 at 11:11
  • 1
    @IulianOnofrei Oh so sorry! The font made it look like a small "L" . Sincere apologies. – Gurtej Singh Aug 06 '15 at 11:17
  • 1
    It Works i putted my "bookmark.json" file in "document". ......Thanks you @IulianOnofrei – mohammad sufyan Aug 06 '15 at 12:55

1 Answers1

20

EDIT: As correctly pointed out by @IulianOnofrei, use the document directory to read/write files and not the resources directory.

Use these methods to read and write data, and your problem should be solved:

- (void)writeStringToFile:(NSString*)aString {

    // Build the path, and create if needed.
    NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* fileName = @"bookmark.json";
    NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];

    if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
        [[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
    }

    // The main act...
    [[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}

- (NSString*)readStringFromFile {

    // Build the path...
    NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* fileName = @"bookmark.json";
    NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];

    // The main act...
    return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}

Code courtesy from another SO answer found here: Writing and reading text files on the iPhone

And of course, the first time you try to read this file from the documents directory you won't get anything, so maybe the first step would be to copy the file there if it does not exist.

Hope this helps.

Gurtej Singh
  • 3,244
  • 1
  • 14
  • 27