我从JSON更新网络数据时遇到大问题。所以我有从JSON URL解析的简单TableView。当我按下按钮时-JSON信息写入tableviewCell,但我需要此信息随时更新。所以我有我的代码:
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSURL *url = [NSURL URLWithString:@"http://url.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webdata = [[NSMutableData alloc]init];
[mytableview reloadData];
}
我写了这段代码,但是我的信息没有更新,我在做什么错?我也尝试过ViewDidAppear,viewWillAppear。但是什么都没有。
添加了cellForRow方法。
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(! cell)
{
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]autorelease];
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
最佳答案
尝试使用基于块的NSURLConnection。我想您形成网络数据的方式就是问题所在。
NSURL *url = [NSURL URLWithString:@"http://url.json"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *urlResponse, NSData * webdata, NSError *reponseError) {
NSArray *json = [NSJSONSerialization JSONObjectWithData: webdata
options:0
error:nil];
for (NSDictionary *person in json) {
//Are these numbers or strings
NSString *art = person[@"artist"];
NSString *song2 = person[@"start"];
[array addObject:art];
[array2 addObject:song2];
}
[mytableview reloadData];
}];
不建议保留两个数组以仅显示歌手姓名和歌曲名称。数据格式正确。这样将这些数据保存在数组中。在
tableView:cellForRowAtIndexPath:
中,当您需要使用索引显示数据时,请提取人员并找到相应的名称和歌曲名称。
关于ios - 如何从JSON更新TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17341502/