Вопрос

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

Это было полезно?

Решение 2

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

Другие советы

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];

I like to use CoreData. Follow those steps:

1-)First of all create a model, and add attribute String type with name jsonvalue.

2-)create this function to save your json file:

    -(void)saveJson:(NSString*)d
    {

       NSString * data = [d retain];

       NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"NameObjectModel" inManagedObjectContext:context]];

    NSError *error = nil;
    NSArray *results = [context executeFetchRequest:request error:&error];
    [request release];
    // error handling code
    if(error){

    }
    else{
        Session* favoritsGrabbed = [results objectAtIndex:0];
        favoritsGrabbed.jsonvalue = data;
    }

    if(![context save:&error]){
        NSLog(@"data saved.");
    }
}

3-)create a function to load your json:

-(void)loadJSONFromFile
{

    //Recover data from core data.

    // Define our table/entity to use
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"NameObjectModel" inManagedObjectContext:context];

    // Setup the fetch request
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];

    // Define how we will sort the records - atributo que sera recuperado
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"jsonvalue" ascending:NO];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];

    [request setSortDescriptors:sortDescriptors];
    [sortDescriptor release];

    // Fetch the records and handle an error
    NSError *error;
    NSMutableArray *mutableFetchResults = [[NSMutableArray alloc]initWithArray:[context executeFetchRequest:request error:&error]];

    if (!mutableFetchResults) {
        // Handle the error.
        // This is a serious error and should advise the user to restart the application
    }

    if(mutableFetchResults.count == 0)
    {
        NSLog(@"the archive is null");
    }

    else if(mutableFetchResults.count > 0)
    {
        NameObjectModel *entity = [mutableFetchResults objectAtIndex:0];
        //NSLog(@"%@",[[entity jsonvalue] JSONValue]);
        NSDictionary * aux = [[entity jsonvalue] JSONValue];

        if([entity jsonvalue]== nil)
        {
            NSLog(@"json is nil");
            NSLog(@"the archive exists but json is nil");
        }

        else {
            // set current json data cache
            [self setJsonCache:aux]; // add to recovery list
        }

    }
    [mutableFetchResults release];
    [request release];
}

Don't forget: NameObjectModel = Name of your NSManagedObject.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top