I am not being able to pass an UIImageView
from a tableView
to a UIViewController
. The image is being displayed in the TableView, but when i try to pass to the other view, it gets nil
The method to download the image is:
func loadImageFromUrl(url: String, view: UIImageView){
// Create Url from string
let url = NSURL(string: url)!
// Download task:
// - sharedSession = global NSURLCache, NSHTTPCookieStorage and NSURLCredentialStorage objects.
let task = URLSession.shared.dataTask(with: url as URL) { (responseData, responseUrl, error) -> Void in
// if responseData is not null...
if let data = responseData{
// execute in UI thread
DispatchQueue.main.async {
view.image = UIImage(data: data)
}
}
}
// Run task
task.resume()
}
And that's how i populate my tableView
:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("UIProductTableViewCell", owner: self, options: nil)?.first as! UIProductTableViewCell
cell.selectionStyle = .none
//Populating data
cell.descriptionLabel.text = catalogOfProducts[indexPath.row].name
cell.priceLabel.text = catalogOfProducts[indexPath.row].regularPrice
if (catalogOfProducts[indexPath.row].productImageURL == "") {
cell.productImageView.image = UIImage(named: "noImage")
}else{
loadImageFromUrl(url: catalogOfProducts[indexPath.row].productImageURL!, view: cell.productImageView)
}
catalogOfProducts[indexPath.row].productImage = cell.productImageView.image
return cell
}
catalogOfProducts[indexPath.row]
is how i pass the UIImage
to the respective object.
To pass the data via segue, i just pass the Product
object:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "productDetailSegue", sender: catalogOfProducts[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let productDetailViewController = segue.destination as! ProductDetailViewController
productDetailViewController.featuredProduct = (sender as? Product)!
}