我有一個來自http://vmg.hdvietpro.com/ztv/home的JSON數據。我想在獲取text1,thumbnailImage值後,單擊getData按鈕以獲取JSON中的text1,thumbnailImage(NSString)值。這是我的代碼,點擊按鈕後沒有任何事情發生。感謝幫助。從JSON獲取數據到表格視圖
@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*[email protected]"Cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIndentifier];
if(!cell){
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier];
}
cell.textLabel.text=[moviesArray objectAtIndex:indexPath.row];
return cell;
}
我得到了connectionDidFinishLoading方法中的數據。真的嗎? – HIEU
你是對的 - 我甚至沒有看到你複製過這個委託。你可以進行調試,看看你是否在填充電影陣列? – LyricalPanda
當你解開它的時候NSLog的每一位 - allDataDictionary,response,hotProgram,itemPageHot,dic,text1。 –