When I'm populating new data in my tableView Controller, my top cell is being rewrite by the bottom one. Let me explain. I have one image that is loading async in the latest cell row, in the bottom. All the other cells are loading static with an image that is in the app. When I scroll down my app and display my bottom cell which have a different image than the others cells, and I scroll up again, I see the first shop image has changed to the dynamic one loaded in the bottom cell. Does anyone know why this is happening?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : shopsTableViewCell = tableView.dequeueReusableCellWithIdentifier("shopCell", forIndexPath: indexPath) as! shopsTableViewCell
cell.index = indexPath.row
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
let apiCall = webApi()
dispatch_async(backgroundQueue, {
apiCall.downloadPhotoAsync("http://api-ytyg.wbbdev.com/files/shops/\(shops[indexPath.row].id)/\(shops[indexPath.row].featured_img)"){(image: UIImage?) -> Void in
dispatch_async(dispatch_get_main_queue()){
if(image != nil){
if (cell.index == indexPath.row){
// shops[indexPath.row].photo = image!
cell.shopImg?.image = image
}
}else{
shops[indexPath.row].photo = UIImage.init(named: "No_Image_Available.jpg")!
}
}
}
})
cell.shopName?.text = shops[indexPath.row].name
cell.shopDescription?.text = shops[indexPath.row].address
cell.label1?.text = shops[indexPath.row].city + " | " + shops[indexPath.row].distance + "Km"
cell.becomeFirstResponder()
return cell
}
it is because your cells are being reused :
so image and other data should be the last image and data of the dequeued cell.
To avoid this, you shall implement
prepareForReuse
in the cell class file to reset data and image. docs of apple about prepareForReuse funcFrom Apple docs :
I think the issue is that while you are scrolling, your images are still in downloading process (that's why you have a nil on that particular line of code). So you have to wait for it.
I am guessing that you have an array of images. If you don't, then you must make one. You must use it like so:
Note: that every time you add downloaded image to this array, you should call
tableView.reloadData()
Using SDWebImage can be far superior. Look at the following code using this library, you just create an instance of UIImageView. then using this library, you can download image directy to imageview instance, and to access the image, you can use imageView.image property of UIImageView class