错误的图像加载到TableView

时间:2019-11-06 23:24:04

标签: swift uitableview nscache

这是我第一次使用NSCache进行表视图。对于cellForRow,我叫NSCache加载图像。该图像有时是错误的图像。我该怎么做才能解决此问题?如果缓存中不包含照片,则将照片替换为“ randomguy”。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyMessagesTableViewCell", for: indexPath) as! MyMessagesTableViewCell
    if let cachedImage = cache.object(forKey: urlArray[indexPath.row] as NSString) as? UIImage {
        cell.proPicImageView.image = cachedImage
        cell.proPicImageView.layer.cornerRadius =
        cell.proPicImageView.frame.size.height / 2
        cell.proPicImageView.layer.masksToBounds = true
        cell.proPicImageView.layer.borderWidth = 0
        cell.usernameLabel.text = usernameArray[indexPath.row]
        cell.messageLabel.text = messageArray[indexPath.row]
        cell.messageLabel.textColor = colorArray[indexPath.row]
        cell.messageLabel.font = fontArray[indexPath.row]
        cell.timeLabel.text = timeArray[indexPath.row]
    } else {
        cell.proPicImageView.image = UIImage(named: "randomguy")
        cell.proPicImageView.layer.cornerRadius =
        cell.proPicImageView.frame.size.height / 2
        cell.proPicImageView.layer.masksToBounds = true
        cell.proPicImageView.layer.borderWidth = 0
        cell.usernameLabel.text = usernameArray[indexPath.row]
        cell.messageLabel.text = messageArray[indexPath.row]
        cell.messageLabel.textColor = colorArray[indexPath.row]
        cell.messageLabel.font = fontArray[indexPath.row]
        cell.timeLabel.text = timeArray[indexPath.row]
    }

    return cell
}

在“查看是否加载”中:          让缓存= NSCache()

    func photoQuery () {
    for username in self.usernameArray {
        let photoQuery = PFQuery(className: "UserPhoto")
        photoQuery.whereKey("username", equalTo: username)
        photoQuery.findObjectsInBackground(block: { (objects: 
        [PFObject]?,error: Error?) in
        if let objects = objects {
            for object in objects {
                if error == nil {
                let userImageFile = object["photo"] as? PFFileObject
                let urlString = userImageFile?.url as! String

                    if let url = URL(string: urlString) {
                        let data = try? Data(contentsOf: url)
                        if let imageData = data {
            self.messageImageArray.append(UIImage(data:imageData)!)
            self.cache.setObject(UIImage(data:imageData)!, forKey: urlString as 
            NSString)
            self.urlArray.append(urlString as NSString)
            print(self.messageImageArray)
                        }
                    }
            }
        }

            }
        })
    }
}

1 个答案:

答案 0 :(得分:0)

这是创建自定义图像视图并在其中具有功能的一种方式,该功能将负责下载图像并将其分配给适当的单元格

let cache = NSCache<NSString, UIImage>()

class CustomImageView: UIImageView {
    var imageURLString: String?

    func startImageDownloadOperation(url: URL) {
        imageURLString = url.absoluteString

        if let cachedVersion = cache.object(forKey: url.absoluteString as NSString) {
            self.image = cachedVersion
        } else {
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                guard error == nil,
                    let response = response as? HTTPURLResponse,
                    response.statusCode == 200 else {
                        DispatchQueue.main.async {
                            self.image = UIImage(named: "default")
                        }
                        return
                }

                DispatchQueue.main.async {
                    if let data = data {
                        let imageToCache = UIImage(data: data)
                        if url.absoluteString == self.imageURLString {
                            self.image = imageToCache
                            cache.setObject(imageToCache!, forKey: url.absoluteString as NSString)
                        }
                    }
                }
            }

            task.resume()
        }
    }
}