从JSON中的URL加载的图像视图在滚动时更改

[英]Imageviews loaded from URLs in JSON change upon scrolling


I'm asynchronously loading image URLs from my JSON file into imageviews on my UITableView. The images load appropriately, however when I scroll down the feed, the user's profile picture changes to the default avatar (used when the user hasn't loaded a personal profile photo). My php has the required if statement to first check if there is a profile pic associated with that user. When the code sees there is no photo associated, it naturally loads the default avatar.

我将我的JSON文件中的图像URL异步加载到我的UITableView上的imageviews中。图像正确加载,但是当我向下滚动源时,用户的个人资料图片会更改为默认头像(当用户未加载个人个人资料照片时使用)。我的php有必要的if语句来首先检查是否有与该用户关联的个人资料照片。当代码看到没有关联的照片时,它自然会加载默认的头像。

So...when the app launches, I see the feed and (after a few seconds...maybe help with that too?) the images in the feed load, but when I scroll past them and return, they are now displayed as the default avatar, and slowly change back to the appropriate associated image. I don't really have a clue where to begin with this...is it a cache issue? Shouldn't the images be loaded before the page loads? Any help with fixing my code is greatly appreciated!

所以...当应用程序启动时,我会看到提要和(几秒钟之后......也许也有帮助?)Feed中的图像加载,但是当我滚过它们并返回时,它们现在显示为默认头像,并慢慢改回相应的关联图像。我真的不知道从哪里开始......这是一个缓存问题吗?不应该在页面加载之前加载图像吗?任何帮助修复我的代码非常感谢!

My PHP file:

我的PHP文件:

$posted="posted";

$query1 = $conn->prepare('SELECT * FROM users WHERE ID=:id');
$query1->bindParam(':id', $_SESSION['uid']);
$query1->execute();
$row = $query1->fetch();
$username="dvdowns";

$zero=0;
$posted="posted";

$query = $conn->prepare('
SELECT description, city, status, state, christmas, country, 
needsusername, howmanypeopleneeded, howmanypeoplesignedup, 
needs.orgname, needs.ID, titleofneed, expiredate, datesubmitted 
FROM needs INNER JOIN follow ON follow.followname = needs.needsusername 
WHERE follow.username = :username AND needs.christmas=:zero 
AND needs.status=:posted ORDER BY datetime DESC LIMIT 0, 10');
$query->bindParam(':username', $username);
$query->bindParam(':zero', $zero);
$query->bindParam(':posted', $posted);
$query->execute();

$arr = array();

while ($rows = $query->fetch()) {
    $title=$rows['titleofneed'];
    $description=$rows['description'];
    $needsusername=$rows['needsusername'];

    $query1 = $conn->prepare('SELECT * FROM users WHERE username=:username');
    $query1->bindParam(':username', $needsusername);
    $query1->execute();
    $row = $query1->fetch();
    $photo=$row['photo'];

    if ($photo=="") {
        $photo = "http://domain.com/images/default.png";
    }
    else {
        $photo="http://www.domain.com/".$photo;
    }

    $arr['needTitle'] = $title;
    $arr['needPoster'] = $needsusername;
    $arr['needDescrip'] = $description;
    $arr['userImage'] = $photo;
    $data[] = $arr;
}

echo json_encode($data);

My TableViewController.m file:

我的TableViewController.m文件:

    NSURL *myURL = [[NSURL alloc]initWithString:@"http://domain.com/json2.php"];
    NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
    NSError *error;

    jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error];

    [tableView reloadData]; // if tableView is unidentified make the tableView IBOutlet
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return jsonArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NeedCardTableViewCell *cell = (NeedCardTableViewCell *) [tableView dequeueReusableCellWithIdentifier:@"needCard" forIndexPath:indexPath];

    NSDictionary *needs = jsonArray[indexPath.row]; // get the data dict for the row
    cell.textNeedTitle.text = [needs objectForKey: @"needTitle"];
    cell.textNeedPoster.text = [needs objectForKey: @"needPoster"];
    cell.textNeedDescrip.text = [needs objectForKey: @"needDescrip"];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        NSURL *imageURL = [NSURL URLWithString:needs[@"userImage"]];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [cell.imageProfPic setImage:image];
        });
    });

    return cell;

1 个解决方案

#1


0  

Use this code below:

使用以下代码:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {

        NeedCardTableViewCell *cell = (NeedCardTableViewCell *) [tableView dequeueReusableCellWithIdentifier:@"cell"];

        if (cell == nil)
        {
            cell = [[NeedCardTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        }

        NSDictionary *needs = jsonArray[indexPath.row]; // get the data dict for the row
        cell.textNeedTitle.text = [needs objectForKey: @"needTitle"];
        cell.textNeedPoster.text = [needs objectForKey: @"needPoster"];
        cell.textNeedDescrip.text = [needs objectForKey: @"needDescrip"];

cell.tag = indexPath.row;

cell.imageView.image = nil;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(queue, ^(void) {

            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:needs[@"userImage"]];

            UIImage* image = [[UIImage alloc] initWithData:imageData];
            if (image) {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     if (cell.tag == indexPath.row) {
                         cell.imageView.image = image;
                         [cell setNeedsLayout];
                     }
                 });
             }
        });

        return cell;
    }

Also be sure that you have registered it in viewDidLoad method if create cell from code:

如果从代码创建单元格,还要确保已在viewDidLoad方法中注册它:

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];

If you are using storyboard cell prototype just skip this line.

如果您正在使用storyboard cell原型,请跳过此行。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/04/16/159de88f703939ac98e7aa84801737ed.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com