Проблемы с анализом JSON и отображением его в UITableView - PullRequest
1 голос
/ 17 декабря 2011

У меня есть этот URL: http://maps.google.com.br/maps/api/directions/json?origin=porto+alegre&destination=novo+hamburgo&sensor=false

И этот код:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];

NSMutableDictionary *theDictionary = [responseString JSONValue];

NSLog(@"%@", theDictionary);

[responseString release];
if (theDictionary != nil) 
{
    NSArray *routesArray = [theDictionary objectForKey:@"routes"];
    NSDictionary *firstRoute = [routesArray objectAtIndex:0];
    NSArray *legsArray = [firstRoute objectForKey:@"legs"];
    NSDictionary *firstLeg = [legsArray objectAtIndex:0];
    steps = [firstLeg objectForKey:@"steps"];
}

[tableView reloadData];

}

Я хочу отобразить каждый @ @ html_instructions "в uitableview.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [self.steps count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cachedCell"];

if (cell == nil)
    cell = [[[UITableViewCell alloc] 
             initWithFrame:CGRectZero reuseIdentifier:@"cachedCell"] autorelease];

return cell;

}

Чего не хватает в моем коде ???Должна быть небольшая деталь ... любая помощь будет БОЛЬШОЙ!

Ответы [ 3 ]

1 голос
/ 08 ноября 2012

Я бы сделал это следующим образом: создайте URL-запрос с вашим URL

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
        [request setURL:[NSURL URLWithString:@"http://maps.google.com.br/maps/api/directions/json?origin=porto+alegre&destination=novo+hamburgo&sensor=false"]];

, затем создайте структуру NSData, которая содержит ответ на запрос, и я преобразовал его в строку

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

После этого вы загружаете JSON в словарь, затем, чтобы переместиться на один уровень вниз, передайте его в другой словарь (результат 1)

NSError *error=nil;
    result = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
    result1 = [result objectForKey:@"routes"];
    result2 = [result1 objectForKey:@"legs"];

Затем переместите его в NSMutableArray

jsonMutArray= [result2 objectForKey:@"steps"];

Изтам вы просто помещаете метку в свою пользовательскую ячейку, присоединяете ее как IBOutlet, синтезируете и выполняете в методе cellForRowAtIndexPath

cell.yourLabel.text = [jsonMutArray objectForKey:@"html_instructions"];

Однако имейте в виду, что я только начинающий, так что этосамый эффективный способ сделать это :) Удачи!

0 голосов
/ 09 марта 2012

Вам не нужно делать что-то подобное в вашем CellForRowAtIndexPath?

NSString *cellValue = **WHATEVER VALUE YOU WANT TO PUT IN**;

cell.textLabel.text = cellValue;

return cell;

Я не вижу, как вы добавляете свои данные в ячейку.

0 голосов
/ 19 декабря 2011

http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/ Может быть, эта статья будет полезна для вас ..

Если после прочтения статьи возникнут какие-либо проблемы, постучите по мне

...