我有来自http://vmg.hdvietpro.com/ztv/home的JSON数据。我想在单击getData按钮后获取text1,thumbnailImage(NSString)值从JSON到表视图后,在此JSON中获取text1,thumbnailImage值。这是我的代码,单击按钮后没有任何反应。谢谢你的帮助。
@interface ViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *moviesArray;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[self myTableView]setDelegate:self];
[[self myTableView]setDataSource:self];
moviesArray=[[NSMutableArray alloc]init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"Fail");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSDictionary *allDataDictionary=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *response=[allDataDictionary objectForKey:@"response"];
NSDictionary *hotProgram=[response objectForKey:@"hot_program"];
NSArray *itemPageHot=[hotProgram objectForKey:@"page"];
for (NSDictionary*dic in itemPageHot) {
NSString *text1=[dic objectForKey:@"text1"];
[moviesArray addObject:text1];
}
[[self myTableView]reloadData];
}
- (IBAction)getData:(id)sender {
NSURL *url=[NSURL URLWithString:@"http://vmg.hdvietpro.com/ztv/home"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(connection){
webData =[[NSMutableData alloc]init];
NSLog(@"ket noi thanh cong");
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [moviesArray count];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString*CellIndentifier=@"Cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIndentifier];
if(!cell){
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier];
}
cell.textLabel.text=[moviesArray objectAtIndex:indexPath.row];
return cell;
}
答案 0 :(得分:0)
您没有正确遍历字典。密钥page
是密钥itemPage
的子项,因此这应该可以正常工作
NSArray *itemPageHot = [[hotProgram objectForKey:@"itemPage"] objectForKey:@"page"];
我建议您下载JSON检查程序以解决此类问题。应用程序商店中的VisualJSON就是我使用的。