Swift: Display image from UIImage array in table view

2.9k views Asked by At

I am getting images from an async request and adding them to a [UIImage]() so that I can populate my UITableView images with those from the array. The problem is, I keep getting Fatal error: Array index out of range in the cellForRowAtIndexPath function when this is called, and I suspect it may be because I'm making an async call? Why can't I add an image from the array to the table view row?

   var recommendedImages = [UIImage]()

        var jsonLoaded:Bool = false {
            didSet {
                if jsonLoaded {

                    // Reload tableView on main thread
                    dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { // 1
                        dispatch_async(dispatch_get_main_queue()) { // 2
                            self.tableView.reloadData() // 3
                        }
                    }

                }
            }
        }

    override func viewDidLoad() {
            super.viewDidLoad()

           // ...

          let imageURL = NSURL(string: "\(thumbnail)")

          let imageURLRequest = NSURLRequest(URL: imageURL!)

          NSURLConnection.sendAsynchronousRequest(imageURLRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { response, data, error in

          if error != nil {

              println("There was an error")

         } else {

              let image = UIImage(data: data)

              self.recommendedImages.append(image!)

              self.jsonLoaded = true

         }

        })

    }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var songCell = tableView.dequeueReusableCellWithIdentifier("songCell", forIndexPath: indexPath) as! RecommendationCell

        songCell.recommendationThumbnail.image = recommendedImages[indexPath.row]


        return songCell
    }

Edit: My numberOfRowsInSection method. recommendedTitles is from the same block of code that I excluded. It's always going to be 6.

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return recommendedTitles.count
    }
1

There are 1 answers

0
Leo On BEST ANSWER

Your error is you return 6 in numberOfRowsInSection,so tableview know that you have 6 cell

But,when execute cellForRowAtIndexPath,your image array is empty,so it crashed.

Try this

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return recommendedImages.count
}

Also switch to main queue,this is enough

 dispatch_async(dispatch_get_main_queue(), { () -> Void in
       self.tableView.reloadData()
    })