JSON图像解析/前缀URL



我已经使用JSON/PHP/MYSQL成功地解析了表视图中的文本和图像。我只将图像的位置存储在数据库中,实际图像存储在服务器上的目录中。数据库中唯一存储的与图像相关的内容是名称。示例car.jpg。我想做的是在我的服务器上为图像位置的URL加前缀,这样就可以解析它们,而无需我进入数据库并手动输入URL。这是我的一些代码。。。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"studentsCell";
    StudentsCell *cell = (StudentsCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"StudentsCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    NSDictionary *studentsDict = [students objectAtIndex:indexPath.row];
    //I want to prefix the URL for the key imagepath but i dont know where and how to do it.
    NSURL *imageURL = [NSURL URLWithString:[studentsDict objectForKey:@"imagepath"]];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *imageLoad = [[UIImage alloc] initWithData:imageData];
    cell.imageView.image = imageLoad;
    NSString *name = [NSString stringWithFormat:@"%@ %@", [studentsDict valueForKey:@"first"], [studentsDict valueForKey:@"last"]];
    cell.title.text = name;
    NSString *subtitle = [NSString stringWithFormat:@"%@", [studentsDict objectForKey:@"email"]];
    cell.subtitle.text = subtitle;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(265, 6, 44, 44);
    [button setImage:[UIImage imageNamed:@"email.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(email:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:button];
   // cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cellbackground.png"]];
    return cell;
}

让我们假设您有这样的东西:

NSURL *baseURL = [NSURL URLWithString:@"http://www.your.site.here/images"]; // whatever the folder with the images is

然后你可以做:

NSURL *imageURL = [baseURL URLByAppendingPathComponent:[studentsDict objectForKey:@"imagepath"]];

顺便说一下,您应该考虑使用UIImageView类别,例如SDWebImage。然后,您可以执行异步图像加载:,而不是同步加载带有图像数据的NSData

[cell.imageView setImageWithURL:imageURL
               placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

占位符是加载图像时应该显示的内容(可能只是一个空白图像),然后SDWebImage将异步检索图像并在检索到图像时更新单元格。这将产生一个响应性更强的用户界面。它还将利用图像缓存(因此,如果你向下滚动然后向上滚动,图像将不会再次检索)。

AFNetworking有一个类似的UIImageView类别,但实现起来不那么健壮。但如果你已经在使用AFNetworking,这是一个选择。

最新更新