2013-02-15 2 views
0

Я пытаюсь выяснить, как получить доступ к json-файлу локально, из приложения. В настоящее время я использую файл JSon удаленно с сервера, как это:Как получить доступ к json-файлу локально из приложения

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]; 

Я попытался это:

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


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

благодаря

ответ

1

могли бы Вы более конкретно? к какому файлу вы пытаетесь получить доступ? вы уже его сохранили?

1/Для главной задачи: вы можете создать dictionnary или массив с путем к файлу

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

2/Но вы можете, как вы написали, читайте «строку» содержимое из файла и затем, в конце концов, разобрать его. Для этого вам нужно (например) этот путь (для «директории» директории, может быть «кэш» реж)

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

И затем использовать «pathToFile» в моем 1 /. Например,

3/Для доступа к Интернету я рекомендую вам проверить AFNetworking. Это лучше делать асинхронной загрузки ;-) (ваш синхронно)

https://github.com/AFNetworking/AFNetworking

+0

Да, я сохранил его в приложении. – hanumanDev

+0

Как вы его сохранили? какой путь? Вы должны быть в состоянии сделать «обратный» легко :-) – Vinzius

+0

Я скопировал его в проект, так как вы перетащите изображение в приложение ios – hanumanDev

1

Мне нравится использовать CoreData. Выполните следующие действия:

1-) Прежде всего создайте модель и добавьте атрибут String с именем jsonvalue.

2) создать эту функцию, чтобы сохранить файл в формате JSON:

-(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-) создать функцию загрузить 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]; 
} 

Не забывайте: NameObjectModel = Имя ваш NSManagedObject.

+0

Я думаю, вы дали слишком много информации. Он не ищет, как это сделать ;-) – Vinzius

+0

omg. я понял, что он сохранил и загрузил json из вашего веб-сервиса. o_o –

8
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"json"]; 
NSData *jsonData = [NSData dataWithContentsOfFile:filePath]; 
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil]; 
Смежные вопросы