iphone – 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,那么它是一种选择.

点赞