ios - 从 firebase 异步加载图像时出错

标签 ios swift firebase firebase-storage

我已经尝试异步加载图像一段时间了。 当我为此创建一个新类并构建并运行应用程序时,运行时日志中会出现错误

// log
Failed to set (borderWidth) user defined inspected property on ...
could not set nil as the value for the key borderWidth.
could not set nil as the value for the key cornerRadius.

使用扩展而不是类可以,图像加载异步,但是,这样我将无法确保在 ImageView 中加载正确的图像。

//  cell for item at
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell  = collectionView.dequeueReusableCell(withReuseIdentifier: "subscribeCell", for: indexPath) as! subscribeViewCell

    cell.userID = self.users[indexPath.row].userId
    cell.profileName.text = self.users[indexPath.row].fullName
    cell.profileImage.setupWithImageUrl(imageUrl: self.users[indexPath.row].ImagePath)
    checkFollowers(indexPath : indexPath)
    return cell
}

我一直在同一个 View Controller 中使用的类:

下载图像的类:

private var imageCache = [String:UIImage]()

class CustomImageView : UIImageView {

    var lastImageUrl : String?

    func setupWithImageUrl (imageUrl: String) {

        self.contentMode = .scaleAspectFill
        self.clipsToBounds = true
        self.layer.cornerRadius = 14
        self.layer.borderWidth = 0

        lastImageUrl = imageUrl
        if let cachedImage = imageCache[imageUrl] {
            self.image = cachedImage
            return
        }
        guard let url = URL(string: imageUrl) else {
            return
        }
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let error = error {
                print(error)
                return
            }
            guard let data = data else {
                return
            }
            guard let image = UIImage(data : data) else {
                return
                }
            imageCache[url.absoluteString] = image
            }
            if (url.absoluteString != self.lastImageUrl) {
            return
            }
            DispatchQueue.main.async {
                self.image = self.image
            }
        }
    }

最佳答案

为什么“这种方式”无法确保在 ImageView 中加载正确的图像。我读了你的代码,我认为你的代码适合 collectionViewController cellForItemAt

关于ios - 从 firebase 异步加载图像时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51585985/

相关文章:

ios - 如何自定义单元格 View 并使它们以编程方式快速水平滚动

Angular 路由保护的 AngularFireAuth 重定向问题

android - 有没有更好的方法从 React Native 打开 vcf 文件除了 Linking

ios - 如果使用核心图散点图中只有一个值,如何显示单个点

ios - 无法显示跨到另一个 tableview 的 Tableview 和自定义表格单元格

ios - 滚动到 tableview 中的行然后闪烁该行

ios - 我可以用动画围绕中心旋转 UIImage 吗?

ios - 如何从 AVDepthData 缓冲区读取 CGPoint 处的深度数据

firebase - 找不到模块 '@google-cloud/logging'

android - 应用内消息错误