2013-12-09 4 views
0

Ведение JSON работу в моем iPhone приложение, пытаясь перечислить JSON в Tableview, то JSON можно найти здесь: appwhittle.com/api/db_all.phpEXC_BAD_ACCESS код = 1 адрес 0x NSURLConnection JSON

мне нужно этот json для работы с Android и ios, так как я сделал приложение для Android сначала, он работает без проблем на устройстве Android, но я не могу понять, что не так.

SearchViewController.m:

// 
// SearchViewController.m 
// Night Locations 
// 
// Created by Stian Wiik Instebø on 12/9/13. 
// Copyright (c) 2013 Stian Wiik Instebø. All rights reserved. 
// 

#import "SearchViewController.h" 
#import "SBJson4.h" 

@interface SearchViewController() 

@end 

@implementation SearchViewController 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view. 
    self.title = @"Search for location"; 

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 

    NSURL *url = [NSURL URLWithString:@"http://appwhittle.com/api/db_all.php"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    data = [[NSMutableData alloc] init]; 
} 

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData 
{ 
    [data appendData:theData]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 

    news = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
    [mainTableView reloadData]; 
} 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The download could not complete" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil]; 
    [errorView show]; 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
} 

- (int)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [news count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"]; 
    if (cell == nil){ 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"]; 
    } 
    [cell release]; 

    cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"name"]; 

    return cell; 
} 


- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

@end 

SearchViewController.h:

#import <UIKit/UIKit.h> 

@interface SearchViewController : UIViewController { 
    IBOutlet UITableView *mainTableView; 

    NSArray *news; 
    NSMutableData *data; 
} 

@end 

появляется ошибка в строке: cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"name"]; где я получить титул в одной из строк в Tableview.

Какая проблема, это форматирование на json? если это так, есть ли способ обойти это?

Программирование для прошивки 7

Любой помощи очень ценится!

+0

Что такое ** ошибка **? –

+0

Убедитесь, что ваши новости NSArray содержит объекты, отвечающие объектуForKey как NSDictionary. – Engnyl

+0

Ошибка: EXC_BAD_ACCESS (код = 1, адрес = 0x40000000c) –

ответ

2

Не используйте эти многие линии используют ниже код для него:

NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://appwhittle.com/api/db_all.php"]]; 
NSData *returnData = [ NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ]; 
NSString *returnString = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding]; 
NSError *err = nil; 
NSMutableArray *search = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err]; 
NSLog(@"Search %@",search); 
+0

Получение этой ошибки; Символы, отличные от ASCII, не допускаются за пределы литералов и идентификаторов, в NSLog –

+0

Работая как шарм, я могу видеть результат, теперь мне нужно только добавить его в таблицуViewCell –

+0

Конечно, но теперь, как я могу добавить его в ячейка таблицы? –

0

Попробуйте использовать NSMutableArray для сбора данных из connectionDidFinishLoading метода.

1
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [search count]; 
} 


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

    static NSString *[email protected]"cell"; 
    UITableViewCell *utvc = [tableView dequeueReusableCellWithIdentifier:store]; 
    if(utvc == nil) 
    { 
     utvc = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]; 
    } 
    NSString *str = [[[search valueForKey:@"locations"]objectAtIndex:indexPath.row]valueForKey:@"location"]; 
    NSLog(@"%@", str); 
    return utvc; 

} 

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
} 
+0

Нет ошибок, ничего, не отображающих строк:/ –

+0

Возможно, вы не установили делегат из xib, щелкните правой кнопкой мыши по таблице в xib и перетащите делегат на владельца файла. Также источник данных –

+0

im с помощью раскадровки tho? но сделали это с обоими –

Смежные вопросы