1
votes

I'm developing an app in swift that displays images (just like YouTube thumbnails), which once clicked, sends you to a view controller with 'subposts' which are multiple images that explain step-by-step how to accomplish something (using images). I have finished the thumbnail functionality where once you click the thumbnail, it sends you to the 'subposts' view. Now I have to add all of the 'subposts' to a collectionview. I can't seem to figure that out, since i'm using a struct instead of a class SubPost because of how I save the subposts on upload. Might be confusing. If not clear, please let me know, and I will further explain. This is what i've come up with:

struct SubPost: Decodable {
    var pathToImage: [String]?
    var postID: String!
    var userID: String!

    init(pathToImage: [String]? = nil, postID: String? = nil, userID: String? = nil) {
        self.pathToImage = pathToImage
        self.postID = postID
        self.userID = userID
    }

}
func fetchSubPosts() {
    ref.child("subposts").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot) in
        let subpostsSnap = snapshot.value as! [String : AnyObject]
        for (_,subpost) in subpostsSnap {
            if let postID = subpost["postID"] as? String {
                var subposst = SubPost(pathToImage: subpost["pathToImage"] as? [String])
                if let userID = subpost["userID"] as? String {
                    subposst.postID = postID
                    subposst.userID = userID
                }
                self.subposts.append(subposst)
            }
            self.collectionview.reloadData()

        }
    })
    ref.removeAllObservers()
}

This is the collectionView function:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "subPostCell", for: indexPath) as! SubPostCell

    cell.subPostImage.downloadImage(from: self.subposts[indexPath.row].pathToImage)

    return cell
    }

}

There is an error in the line:

cell.subPostImage.downloadImage(from: self.subposts[indexPath.row].pathToImage) With an error of:

Cannot convert value of type '[String]?' to expected argument type 'String?'

Can't seem to figure this out. Any sort of help is very much appreciated! Thanks in advance!

1

1 Answers

1
votes

You declared as an optional string array pathToImage: [String]?, but are then trying to treat it as an optional string. That won't work, which is what the error message points out.

You'll need to indicate in your code what string from the array you want to pass to downloadImage. For example:

cell.subPostImage.downloadImage(from: self.subposts[indexPath.row].pathToImage![0])