如何在ios中使用异步概念在uitableviewcell中显示图像

时间:2014-01-15 07:18:12

标签: ios iphone objective-c json xcode

我必须在UITableView中显示一些帖子博客。当我检索所有Web服务数据时。 这是我的示例代码。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{  
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
NSError *err;
NSString *strResponse=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"response is %@",strResponse);
dit=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&err];

NSArray *arrResults = [dit valueForKey:@"classifieds_mst"];

listOfObjects = [NSMutableArray array];

for(dictRes in arrResults)

{

 Attributes *at = [[Attributes alloc]init];
 at.classimage=[dictRes valueForKey:@"image_name"];
 [listOfObjects addObject:at];

 }

[tableView reloadData];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier=@"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; 
if (cell == nil) 
{  
 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"identifier"];  
}
classifiedimage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 80)];  
[cell.contentView addSubview:classifiedimage];
Attributes *att = [listOfObjects objectAtIndex:indexPath.row];
NSString *str; 
str=att.classimage; 
classifiedimage.image = [UIImage imageNamed:str]; 
return cell;

}

我的要求是我想使用json解析器在uitableviewcells中显示图像。我写了上面的代码。但是图片没有显示在uitableviewcell中。我想使用Asyncronous概念在uitableviewcells中显示图像。请给我任何想法我是编程新手。谢谢。 这是我的json数据。

{"classifieds_mst":[{"classified_id":83,image_name":"1389006378_butterfly.jpeg"},
{"classified_id":82,"image_name":"ttt.jpj"},{"classified_id":83,”image_name":"ttttt.jpj”}

6 个答案:

答案 0 :(得分:0)

imageNamed用于从本地捆绑(在应用程序中)加载图像。

imageWithData:dataWithURL用于从url加载图像。

答案 1 :(得分:0)

通过引用您的JSON数据,它只包含image_name。首先,您需要构建实际的图像URL。 (在浏览器中复制粘贴实际网址以确保图像在服务器中可用)。

获得图片网址后,您可以在单元格中使用AsyncImageView代替UIImageView。它将为您处理异步事件,因为您只需要设置图像URL。这就是要走的路。

还有一个建议是重新检查cellForRowAtIndexPath,因为代码总是创建imageView并在每次创建单元格时添加到单元格。当您重复使用单元格时,这不是必需的。您只需在分配单元格时创建一次图像视图,然后将标记分配给imageview,然后根据此标记获取imageview,然后使用它。仅供参考,我发布了一个示例代码:

if(cell == nil){
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"identifier"]; 
    AsyncImageView *imgView= [[[AsyncImageView alloc]init]autorelease];
    imgView.tag = 1000;
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    [cell.contentView addSubview:imgView];
}
 AsyncImageView *imgView= (AsyncImageView*)[cell.contentView   viewWithTag:1000];
 contactImgView.frame = CGRectMake(0, 0, 300, 80);

 //imgUrl is the actual url of image that is available in datasource
 [contactImgView setImageURL:imgUrl];

希望很清楚。

答案 2 :(得分:0)

您必须在图像名称中附加域名:(image_name“:”1389006378_butterfly.jpeg),以便您可以获取存储在服务器上的图像的URL,现在您可以使用以下代码:

 [cell.yourImageView setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:yourImageNameHere]]]];

答案 3 :(得分:0)

如果您使用AFNetworking,则使用它来下载您的图像,如

    NSArray *keys = @[@"UserID", ];
    NSArray *objects = @[@(userId)];

    NSDictionary *parameter = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:
                                [NSURL URLWithString:BaseURLString]];
    [httpClient setParameterEncoding:AFJSONParameterEncoding];
    [httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                            path:@"UserService.svc/GetUserInfo"
                                                      parameters:parameter];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSError* error = nil;
        id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }];

    [operation start];

和图像使用

[cell.userImage setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:userBasicInfo.imageUrl]]
                                  placeholderImage:[UIImage imageNamed:@"facebook-no-user.png"]
                                           success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
                                               weakCell.userImage.image = image;
                                               [weakCell setNeedsLayout];

                                               } completion:^(BOOL success, NSError *error) {
                                                   NSLog(@"%@",[error localizedDescription]);
                                               }];

                                           }
                                           failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
                                           }];

答案 4 :(得分:0)

您为您的单元格创建UITableViewCell的子类(可以称之为blogTableViewCell),并在表格中使用它。

使用JSON数据初始化blogTableViewCell(您可以使用NSDictionary存储JSON信息)

在blogTableViewCell中创建一个函数,在另一个线程上加载图像数据(所以主线程可以继续它的过程),一旦图像被加载,更新单元格上的uiimageview以显示它(这应该在主线程上完成)因为它是一个UI更新)

答案 5 :(得分:0)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...
    //cell.textLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"name"];
    cell.detailTextLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"designation"];
    cell.imageView.image=[UIImage imageNamed:[[resultArray objectAtIndex:indexPath.row] valueForKey:@"image"]] ;

    //[cell.imageView setImageWithURL:[NSURL URLWithString:[[resultArray objectAtIndex:indexPath.row] objectForKey:@"image"]]];
  //  NSURL *url = [NSURL URLWithString:[resultArray objectAtIndex:indexPath .row]];
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[resultArray objectAtIndex:indexPath.row] valueForKey:@"image"] ]];
    cell.imageView.image = [UIImage imageWithData:imageData];



    return cell;
}