将来自 firebase 图像 URL 的图像设置为 Swift 中的单元格

Set image from firebase image URL to a cell in Swift

如果 ImageView 在同一个视图控制器中,我就能让它工作。但是我创建了一个自定义单元格 .xib 和一个模型 class。所有数据(文本)似乎都在传输,甚至是 Firebase 数据库图像的 URL,但图像没有改变,显示的是默认占位符图像。如果我不设置默认占位符图像,我会收到一条错误消息,指出它为 nil。同样,所有单元格都在填充来自 Firebase 的文本数据,唯一不是来自给定 [=21 的图像=].调试显示 URL 确实传递到 "profileImageURL" 变量中。这是一些代码:

class Profile{

var name: String = ""
var age: String = ""
var profileImg : UIImageView! = UIImageView.init(image: "main"))
var description : String = ""


 }

这里是 table 视图控制器代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCellTableViewCell", for: indexPath) as! CustomCellTableViewCell

    let profile = profileArray[indexPath.row]
    // Configure the cell...
    profileTableView.rowHeight = 300
    cell.nameLbl.text = profile.name
    cell.descriptionLbl.text = profile.description
    cell.profileImage.image = UIImage(named: "main")

    return cell
}

func retrievePosts(){


    let dataRef = Database.database().reference()

    let postsDB = dataRef.child("Messages")

    postsDB.observe(.childAdded) { (snapshot) in
    let value = snapshot.value as! Dictionary<String,String>

    let text = value["postText"]!
    let profileImgURL = value["postImage"]!
    let userID = value["sender"]!

    let url = NSURL(string:"\(profileImgURL)")

    let profile = Profile()
    profile.description = text
    profile.name = name as! String
    profile.profileImg.sd_setImage(with: URL(string:profileImgURL), placeholderImage: nil)  


    self.profileTableView.reloadData()
    self.profileArray.insert(profile, at: 0)

        })

}

here is the firebase data structure:
        - Messages
          -L4IkuSxWDnsiJvTKoo0
              -postImage: "https://firebasestorage.googleapis.co......"
              -postText: "Lorem ipsum dolor sit er elit lamet, consecteta..."
              -sender: "C19ghii6OVPNnzJNYPvVJeKuoi73"

这不是真正的解决方案,而是替代方案:

使用 kingfisher pod 从 URL 设置图像。

let url = URL(string: "https://example.com/image.jpg")!
imageView.kf.setImage(with: url)

https://github.com/onevcat/Kingfisher

兄弟,任何单元格的图像都应该在 cellForRowAt 方法中设置。您正在获取原始数据,因为您是从配置文件而不是硬编码中获取原始数据,而对于图像,您每次都将图像设置为 "main"。希望这可以帮助。 – 阿希什夏尔马

是啊!谢谢! App 开发新手。就是这样。必须在 Profile 中创建一个新变量来保存 url,然后在 cellForRowAt 中使用该变量 URL 设置 Imageview。很可能有一种更简单的方法可以做到这一点,但对我有用!太感谢了! – 吉列尔莫·格雷科