estelyk
estelyk

Reputation: 25

can't delete the correct picture from firebase in uicollectionview using swift

so, I have a collectionview that contains images downloaded from firebase. Each cell has a delete button. Im trying to allow users to delete the images. So far I am able to delete the cell. But then the wrong firebase image is deleted, so when the collectionview is reloaded, it still shows the image that I intend to delete. Please help

 var profileImageUrl: String?

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! createProfilePicCollectionViewCell
     cell.picCellPic.loadImageUsingCacheWithUrlString(urlString: imageUrlArray[indexPath.item])



    profileImageUrl = imageUrlArray[indexPath.item]


    cell.deleteButton?.tag = indexPath.row
    cell.deleteButton?.addTarget(self, action: #selector(deleteUser(sender:)), for: UIControlEvents.touchUpInside)


 return cell

}

I'm trying to reference the correct image URL using the variable 'profileImageUrl' from the collectionview cell so that I can properly delete them. But it seems like the variable references the wrong URL. Here's the delete function:

 @objc func deleteUser(sender:UIButton) {

    if let user = Auth.auth().currentUser {
        let UID = user.uid

        let storageRef = Storage.storage().reference(forURL: self.profileImageUrl!)

        ref.removeValue { error, _ in

        }
    }

    let i = sender.tag
    imageUrlArray.remove(at: i)
    collectionViewController.reloadData()

 }

Thank you!

Upvotes: 0

Views: 53

Answers (1)

Steve Hancocks
Steve Hancocks

Reputation: 209

From the code you have posted your profileImageUrl variable is within the UIViewController and not within the UICollectionViewCell.

Therefore you're setting it every time a cell is dequeued. I imagine it then always deletes the image at the url from the last cell that was loaded.

Move the profileImageUrl variable within the cell class.

Also, your deleteUser method in your UIViewController or your UICollectionViewCell subclass? It may make more sense to have it in the cell class as you need to get a handle on the profileImageUrl variable.

Upvotes: 1

Related Questions