Adrian Navarro
Adrian Navarro

Reputation: 135

Trying to pass Image from UICollectionView loaded from Firebase, to another VC

The problem i'm having is setting the image from my MainDetailVC to the image in the cell selected in my Main View controller. I keep getting a nil value for desVC.detailImage.image . If anyone has any tips, that would be awesome.

Still pretty new to swift so please excuse any ignorance on my end. lol

Thank you!

import UIKit
import Firebase
import FirebaseDatabase
import SDWebImage

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, ImageCellDelegate {




@IBOutlet weak var popImageCollection: UICollectionView!
@IBOutlet weak var imageCollection: UICollectionView!


var customImageFlowLayout = CustomImageFlowLayout()
var popImageFlowLayout = PopImagesFlowLayout()
var images = [BlogInsta]()
var popImageArray = [UIImage]()
var homePageTextArray = [NewsTextModel]()

var dbRef: DatabaseReference!
var dbPopularRef: DatabaseReference!

override func viewDidLoad() {
    super.viewDidLoad()
    dbRef = Database.database().reference().child("images")
    dbPopularRef = Database.database().reference().child("popular")
    loadDB()
    loadImages()
    loadText()
    customImageFlowLayout = CustomImageFlowLayout()
    popImageFlowLayout = PopImagesFlowLayout()

    imageCollection.backgroundColor = .clear
    popImageCollection.backgroundColor = .white


    // Do any additional setup after loading the view, typically from a nib.
}
func loadText() {
    dbRef.queryOrdered(byChild: "order").observe(DataEventType.value, with: { (snapshot) in
        if snapshot.childrenCount > 0 {
            self.homePageTextArray.removeAll()
            for homeText in snapshot.children.allObjects as! [DataSnapshot] {
                let homeTextObject = homeText.value as? [String: AnyObject]
                let titleHome = homeTextObject?["title"]
                let categoryButtonText = homeTextObject?["category"]
                self.imageCollection.reloadData()
                let homeLabels = NewsTextModel(title: titleHome as! String?, buttonText: categoryButtonText as! String?)
                self.homePageTextArray.append(homeLabels)
            }
        }
    })
}
func loadImages() {
    popImageArray.append(UIImage(named: "2")!)
    popImageArray.append(UIImage(named: "3")!)
    popImageArray.append(UIImage(named: "4")!)

    self.popImageCollection.reloadData()
}
func loadDB() {
    dbRef.queryOrdered(byChild: "order").observe(DataEventType.value, with: { (snapshot) in
        var newImages = [BlogInsta]()
        for BlogInstaSnapshot in snapshot.children {
            let blogInstaObject = BlogInsta(snapshot: BlogInstaSnapshot as! DataSnapshot)
            newImages.append(blogInstaObject)
}
self.images = newImages
self.imageCollection.reloadData()
})

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView == self.imageCollection {
       return images.count
    } else {
        return popImageArray.count
    }

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if collectionView == self.imageCollection {
   let cell = imageCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ImageCollectionViewCell
        cell.delegate = self
        cell.contentView.backgroundColor = UIColor.clear
    let image = images[indexPath.row]
        let text: NewsTextModel
        text = homePageTextArray[indexPath.row]
        cell.categoryButton.setTitle(text.buttonText, for: .normal)
        cell.newTitleLabel.text = text.title
    cell.imageView.sd_setImage(with: URL(string: image.url), placeholderImage: UIImage(named: "1"))
        return cell
    } else {
       let cellB = popImageCollection.dequeueReusableCell(withReuseIdentifier: "popCell", for: indexPath) as! PopularCollectionViewCell
        let popPhotos = popImageArray[indexPath.row]
        cellB.popularImageView.image = popPhotos
        cellB.popularImageView.frame.size.width = view.frame.size.width
            return cellB
    }

}


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let desVC = mainStoryboard.instantiateViewController(withIdentifier: "MainDetailViewController") as! MainDetailViewController
    let imageIndex = images[indexPath.row]

    let imageURLString = imageIndex.url
    print(imageURLString)
    let imageUrl:URL = URL(string: imageURLString)!
    let imageData: NSData = NSData(contentsOf: imageUrl)!
    let image = UIImage(data: imageData as Data)
    desVC.detailImage.image = image
    performSegue(withIdentifier: "toDetails", sender: self)

}


func MusicWasPressed() {
    performSegue(withIdentifier: "homeToMusic", sender: self)
}

func SneakersWasPressed() {
    performSegue(withIdentifier: "homeToSneakers", sender: self)
}

func RandomWasPressed() {
    performSegue(withIdentifier: "homeToRandom", sender: self)
}

func FashionWasPressed() {
    performSegue(withIdentifier: "homeToFashion", sender: self)
}
func EntertainmentWasPressed() {
    performSegue(withIdentifier: "homeToEntertainment", sender: self)
}


}

Upvotes: 1

Views: 245

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

The problem is that you don't pass it here

 performSegue(withIdentifier: "toDetails", sender: self)

you create a desVC without a push , and use a segue , Also don't do

let imageData: NSData = NSData(contentsOf: imageUrl)!

as it blocks the main thread i recommend sending the url of the image and load it there say with SDWebImage

//

First to clarify you have 2 options first is creating a desVC as you did and init it with sended parameters then push to self.navigationController OR use a segue When you use segues and want to send data to destination implement prepare(for segue , so refactor to

1-

 performSegue(withIdentifier: "toDetails", sender: imageURLString )

2-

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toDetails" { 
       let nextScene = segue.destination as? MainDetailViewController {
          nextScene.imageURLString = sennder as! String
          nextScene.sendedTitle = self.sendedTitle
       } 

    }
}

3- Don't access UI elements before the destinationVC is presented

Upvotes: 1

Related Questions