0

I can't save string to JSON on device, but in simulator can!

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Warehouse" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];

NSMutableArray *arJson = [[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil] mutableCopy];

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:prod.title,@"title",
                                                                   prod.price,@"price",
                                                                   prod.descrip,@"descrip",nil];

[arJson addObject:dic];

NSData * data = [NSJSONSerialization dataWithJSONObject:arJson options:NSJSONWritingPrettyPrinted error:nil];
NSString * myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

[[myString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:filePath atomically:YES];
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Jon S.
  • 1
  • 2
  • Are u sure the resource path is stay in your app document not some where in your Mac's project folder or sth? – Tj3n Dec 25 '15 at 09:20
  • 1
    I think this is what your looking for http://stackoverflow.com/questions/5853014/file-write-with-nsbundle-mainbundle-fails – LeviXC Dec 25 '15 at 09:21

1 Answers1

2

You can't change files in you main bundle folder. Check full answer here: https://stackoverflow.com/a/10671119/1003065

Community
  • 1
  • 1
radya
  • 422
  • 1
  • 5
  • 13
  • Thanks you, error was in url. This is correct: NSString *filePath = [NSString localizedStringWithFormat:@"%@/%@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0], @"Warehouse.json"]; – Jon S. Dec 25 '15 at 09:41