Search code examples
iosswiftfirebasesdwebimage

Set image from firebase image URL to a cell in Swift


I am able to get it working if the ImageView is in the same View Controller. But I created a custom cell .xib and a model class. All data (text) seems to be transferring, even the URL of the Firebase database image, but the image doesn't change, the default placeholder image is showing. If I don't set the default placeholder image, I will get an error saying that it is nil.. Again, all cells are populating text data from Firebase, the only thing that isn't is the image from the given URL. Debugging shows that the URL does get passed into the "profileImageURL" variable. Here is some of the code:

class Profile{

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


 }

Here is the table view controller code:

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"

Solution

  • bro, the image for any cell is meant to be set in cellForRowAt method. You are getting the raw data because you are fetching it from profile instead of hardcoding, whereas for the image you are setting the image as "main" each time. Hope this helps. – Ashish Sharma

    Yup! Thank you! New to App dev. That was it. Had to create a new variable in Profile to hold the url and then in cellForRowAt set the Imageview with that variable URL. There is most likely an easier way to do it but worked for me! Thank you so much! – Guillermo Greco