iphoneiosobjective-cjsoninitwithcontentsoffile

How to access a json file locally from within the app


I'm trying to figure out how to access a json file locally, from within the app. Currently I've been using the json file remotely from a server like this:

jsonStringCategory = @"http://****categories?country=us";
    }

    // Download the JSON file
    NSString *jsonString = [NSString
                            stringWithContentsOfURL:[NSURL URLWithString:jsonStringCategory]
                            encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
                            error:nil];

    NSLog(@"jsonStringCategory is %@", jsonStringCategory);

    NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];

    // Create parser 
    SBJSON *parser = [[SBJSON alloc] init];
    NSDictionary *results = [parser objectWithString:jsonString error:nil];

    itemsTMP = [results objectForKey:@"results"];

    self.arForTable = [itemsTMP copy];

    [self.tableView reloadData];

I tried this:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"categoriesus" ofType:@"json"];


    jsonStringCategory = [[NSString alloc] initWithContentsOfFile:filePath];

thanks


Solution

  • Could you be more specific? which file do you try to access? did you already save it?

    1/ For your main problem: you can create a dictionnary or array with a file path

    [NSDictionary dictionaryWithContentsOfFile:<#(NSString *)#>]
    [NSArray arrayWithContentsOfFile:<#(NSString *)#>]
    

    2/ But you can, as you wrote it, read the "string" content from a file and then, eventually, parse it. For that you need (for example) a path like this (for the "directory" dir, could be the "cache" dir)

    NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *pathToFile = [ [ [ [ array objectAtIndex:0 ] stringByAppendingPathComponent:@"nameOfTheFile" ] stringByAppendingString:@".ext" ] retain ];
    

    And then use "pathToFile" in my 1/ example.

    3/ For your internet access, I recommend you to check AFNetworking. It's better to do async download ;-) (yours is synchronous)

    https://github.com/AFNetworking/AFNetworking