2013-08-14 3 views
-1

이것은 내 ViewController.h에서 코드 다음 ViewController.m 여기iOS 앱에서 JSON 배열을 UITableView로 읽으시겠습니까?

#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController 
{ 
    IBOutlet UITableView *mainTableView; 

    NSArray *news; 
    NSMutableData *data; 
} 

@end 

그리고있다 : 지금까지 내가 말할 수있는

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.title = @"News"; 

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 

    NSURL *url = [NSURL URLWithString:@"http://google.com/external/search?query=hello"]; 
    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; 
    NSArray *responseDict = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil]; 
    news = [responseDict objectAtIndex:0]; 
    [mainTableView reloadData]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The download could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles: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:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"]; 
    } 

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

    return cell; 
} 

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

@end 

, 사전에 JSON을두고 코드로 잘못 그것은 존재하지 않는 인덱스를 찾으려고합니다. 대신 사전에 JSON 배열을 읽을 수 있도록이 코드를 변경하는 방법이 있습니까?

업데이트 :

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.title = @"News"; 

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 

    NSURL *url = [NSURL URLWithString:@"http://google.com/external/search?query=hello"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    [NSURLConnection connectionWithRequest: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; 
    NSArray *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL]; 
    //news = [responseDict objectAtIndex:0]; 
    // [mainTableView reloadData]; 
    if ([responseDict isKindOfClass:[NSArray class]]) { 
     news = responseDict; 
     [mainTableView reloadData]; 
    } else { 
     NSLog(@"JSON Error."); 
    } 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The download could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; 
    [errorView show]; 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
} 

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

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

NSString *_getString(id obj) 
{ 
    return [obj isKindOfClass:[NSString class]] ? obj : nil; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"]; 

    if(cell == nil){ 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"]; 
    } 

    cell.textLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:@"metaScore"]); 
    cell.detailTextLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:@"title"]); 

    return cell; 
} 

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

@end 
+1

NSlog은'responseDict가' –

+0

은'nil'는, 문자열을 확인하십시오 -이

/* connectionDidFinishLoading */ // NSArray *responseDict = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil]; NSArray *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL]; //news = [responseDict objectAtIndex:0]; // [mainTableView reloadData]; if ([responseDict isKindOfClass:[NSArray class]]) { news = responseDict; [mainTableView reloadData]; } else { NSLog(@"JSON Error."); } 

'data'라고 쓰고 그것을 기록하십시오. – Kevin

+0

JSON에 닫는 문자가 없거나 오타가있는 것 같습니다. 또한 그것은 3 NSDictionaries의 배열처럼 보입니다. 일반적으로 전체 JSON은 {}을 루트로 포함합니다. {[{dictionary1, dictionary2, dictionary3}] – Zhang

답변

2

변화

news = [responseDict objectAtIndex:0]; 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection에서

news = responseDict; 

에 방법 : 여기 내하는 .m 파일에 새로운 코드입니다.

업데이트 :

/* -viewDidLoad, just fix warning "unused var" */ 
// [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
[NSURLConnection connectionWithRequest:request delegate:self]; 

-`responseDict` 인 경우

NSString *_getString(id obj) 
{ 
     return [obj isKindOfClass:[NSString class]] ? obj : nil; 
} 

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

     // cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"metaScore"]; 
     // cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"title"]; 

     /** Your JSON value maybe NSNull */ 
     cell.textLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:@"metaScore"]); 
     cell.detailTextLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:@"title"]); 

     return cell; 
} 
+0

그러면 테이블 뷰 데이터를 성공적으로로드 할 수 있습니까? – Someone

+0

@ Someone 위의 코드에 따르면 tableView는 서버의 전체 JSON 데이터를 표시하지만 실수로 JSON 데이터의 첫 번째 요소를 변수 'news'에 넣었습니다. 또한,'new'는 NSArray 타입입니다 만,'[responseDict objectAtIndex : 0]'는 NSDictionary –

+0

아니요, 작동하지 않습니다. –

관련 문제