Trying to load images in tableView asynchronously in (Xcode 9 and Swift 4) and seems I have a correct way but my code stops working if I scroll my tableView fast. So basically I had found nil error.
Here is my code:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
let feed = feeds[indexPath.row]
cell.titleLabel.text = feed.title
cell.pubDateLabel.text = feed.date
cell.thumbnailImageView.image = nil
if let image = cache.object(forKey: indexPath.row as AnyObject) as? UIImage {
cell.thumbnailImageView?.image = image
} else {
let imageStringURL = feed.imageUrl
guard let url = URL(string: imageStringURL) else { fatalError("there is no correct url") }
URLSession.shared.downloadTask(with: url, completionHandler: { (url, response, error) in
if let data = try? Data(contentsOf: url!) {
DispatchQueue.main.async(execute: {
guard let image = UIImage(data: data) else { fatalError("can't create image") }
let updateCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell // fast scroll issue line
updateCell.thumbnailImageView.image = image
self.cache.setObject(image, forKey: indexPath.row as AnyObject)
})
}
}).resume()
}
return cell
}
I have issue on the line:
let updateCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
If I scroll down slowly everything works just fine and no mistakes appear.
Does anyone know where I've made a mistake?
This may happens if cell you are trying to get using tableView.cellForRow(at:) is not visible currently.
To avoid crash you can use optionals as:
let updateCell = tableView.cellForRow(at: indexPath) as? CustomTableViewCell // fast scroll issue line
updateCell?.thumbnailImageView.image = image
Keep everything as it is, I hope it should work without any errors.
You can consider one of popular UIImage extension libs, like I said in comment for example AlamofireImage and set thumbnail with the placeholder, as soon as image will be ready it will be replaced automatically.
One more thing I change no need to have updateCell I removed it.
Please add placeholder image and test it should work, sorry I didn't fully check syntax.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
let feed = feeds[indexPath.row]
if let image = cache.object(forKey: indexPath.row as AnyObject) as? UIImage {
cell.thumbnailImageView?.image = image
} else {
let imageStringURL = feed.imageUrl
guard let url = URL(string: imageStringURL) else { fatalError("there is no correct url") }
cell.thumbnailImageView.af_setImage(withURL : url, placeholderImage: <your_placeholderImage>)
return cell
}
Related
I have this huge problem! I'm fetching data from firebase, saving it to an array and then using cellForRowAt I populate the row. In the end I run tableView.reload(). I have to run tableView.reload() because cellForRowAt runs before the array can populate with db elements.
The problem is that when I run tableView.reload() the app freezes and if I click any button it won't work. The button runs only when tableView.reload() finished running.
I run tableView.reload() as soon as the array have been populated.
Some code:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ImageTableViewCell
let preview2 = imageDownload(images[counter!]["previewURL"]! as! String)
cell.img2.imagePreview = preview2
cell.img2.setImage(preview2, for: .normal)
cell.img2.addTarget(self, action: #selector(imgTapped(_:)), for: .touchUpInside)
let preview1 = imageDownload(images[counter!-1]["previewURL"]! as! String)
cell.img1.imagePreview = preview1
cell.img1.setImage(preview1, for: .normal)
cell.img1.addTarget(self, action: #selector(imgTapped(_:)), for: .touchUpInside)
counter = counter! - 2
return cell
}
func imageDownload(_ url: String) -> UIImage {
let imageURL = URL(string: url)
let imageData = try? Data(contentsOf: imageURL!)
let image = UIImage(data: imageData!)
return image!
}
class ImageTableViewCell: UITableViewCell {
#IBOutlet var img1: ExtendedButton!
#IBOutlet var img2: ExtendedButton!
}
The problem is in using
let imageData = try? Data(contentsOf: imageURL!)
that blocks the current main thread not because of tableView.reloadData() , you better use SDWebImage
images are not showing properly in tableview , I have two Json Api (Primary/high) school. I can append the Both Json api Data and display into tableview,
tableview working fine it's showing both(primary/high) school data. when I can scroll the tableview images are jumping and images loading very slow in image view at tableview.
Before scrolling tableview its showing like this
After scrolling the tableview it's shows like this
after scrolling images are jumping,
this is the code
var kidsdata = [KidDetails]()
func getprimarydata(_firsturl: String,firstid:String,updatedate:String)
{
if errorCode == "0" {
if let kid_list = jsonData["students"] as? NSArray {
self.kidsdata.removeAll()
for i in 0 ..< kid_list.count {
if let kid = kid_list[i] as? NSDictionary {
let imageURL = url+"/images/" + String(describing: kid["photo"]!)
self.kidsdata.append(KidDetails(
name:kid["name"] as? String,
photo : (imageURL),
standard: ((kid["standard"] as? String)! + "std" + " " + (kid["section"] as? String)! + " section ")
))}}}}
}
func gethighdata(_secondurl:String ,secondid:String,updatedate:String)
{
if errorCode == "0" {
if let kid_list = jsonData["students"] as? NSArray {
for i in 0 ..< kid_list.count {
if let kid = kid_list[i] as? NSDictionary {
let imageURL = url+"/images/" + String(describing: kid["photo"]!)
self.kidsdata.append(KidDetails(
name:kid["name"] as? String,
photo : (imageURL),
standard: ((kid["standard"] as? String)! + "th" + " " + (kid["section"] as? String)! + " section ")
)
)
}
}
self.do_table_refresh()
}
}
}
func do_table_refresh()
{
DispatchQueue.main.async(execute: {
self.TableView.reloadData()
return
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCell(
withIdentifier: "cell", for: indexPath) as! DataTableViewCell
cell.selectionStyle = .none
cell.ProfileImage?.image = nil
let row = (indexPath as NSIndexPath).row
let kid = kidsdata[row] as KidDetails
cell.NameLabel.text = kid.name
cell.ProfileImage.image = UIImage(named: "profile_pic")
cell.ProfileImage.downloadImageFrom(link:kid.photo!, contentMode: UIViewContentMode.scaleAspectFill)
cell.ClassNameLabel.text = kid.standard
return cell
}
where I did mistake pls help me....!
AlamofireImage handles this very well. https://github.com/Alamofire/AlamofireImage
import AlamofireImage
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DataTableViewCell
cell.selectionStyle = .none
let kid = kidsdata[indexPath.row] as KidDetails
cell.NameLabel.text = kid.name
cell.ClassNameLabel.text = kid.standard
// assuming cell.ProfileImage is a UIImageView
cell.ProfileImage.image = nil
let frame = CGSize(width: 50, height: 50)
let filter = AspectScaledToFillSizeWithRoundedCornersFilter(size: frame, radius: 5.0)
cell.ProfileImage.af_setImage(withURL: urlToImage, placeholderImage: nil, filter: filter,
imageTransition: .crossDissolve(0.3), runImageTransitionIfCached: false)
return cell
}
All we need to do is use the prepareForReuse() function. As discussed in this medium article, This function is called before cell reuse, letting you cancel current requests and perform a reset.
override func prepareForReuse() {
super.prepareForReuse()
ProfileImage.image = nil
}
there! I need your help. I have UIImage inside UICollectionView which lying inside UITableView. When I get data from API at the first time it shows images right, but when I start to scroll down and come back, it shows wrong images. My code looks like this:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! AllPostsOfUserCollectionViewCell
let post = allPostsOfUserArray[collectionView.tag]
if post.imageLinks.count != 0 {
let imageLink = post.imageLinks[indexPath.row]
if imageLink.imageLink != nil {
let url = URL(string: imageLink.imageLink!)
cell.imageOfAnimalInCollectionView.sd_setImage(with: url!, placeholderImage: UIImage(named: "App-Default"),options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in
})
}
}
return cell
}
My model looks like this:
class UserContent {
var name = ""
var imageLinks = [UserImages]()
init(name: String, imageLinks: [UserImages]?) {
self.name = name
if imageLinks != nil {
self.imageLinks = imageLinks!
}
}
init() { }
deinit {
imageLinks.removeAll()
}
}
class UserImages {
var imageLink: String?
init(imageLink: String?) {
self.imageLink = imageLink
}
init() { }
deinit {
imageLink = ""
}
}
What I do in UITableView
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let index = indexPath.row
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! AllPostsOfUserTableViewCell
cell.collectionView.tag = index
let post = allPostsOfUserArray[index]
if post.imageLinks.count == 0 {
cell.collectionView.isHidden = true
} else {
cell.collectionView.isHidden = false
}
return cell
}
UPD: I added cell.collectionView.reloadData() to func tableView(cellForRowAt indexPath). Now it works fine.
Could you try this code:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! AllPostsOfUserCollectionViewCell
cell.imageOfAnimalInCollectionView.image = UIImage(named: "App-Default")
let post = allPostsOfUserArray[collectionView.tag]
if post.imageLinks.count != 0 {
let imageLink = post.imageLinks[indexPath.row]
if imageLink.imageLink != nil {
let url = URL(string: imageLink.imageLink!)
cell.imageOfAnimalInCollectionView.sd_setImage(with: url!, placeholderImage: UIImage(named: "App-Default"),options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in
})
}
}
return cell
}
This problem is something like race condition.
You can reference my answer in similair question
You might need to find another module to download image and set to cell manually.
cell.imageOfAnimalInCollectionView.image = nil
if post.imageLinks.count != 0 {
let imageLink = post.imageLinks[indexPath.row]
if imageLink.imageLink != nil {
let url = URL(string: imageLink.imageLink!)
cell.imageOfAnimalInCollectionView.sd_setImage(with: url!, placeholderImage: UIImage(named: "App-Default"),options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in
})
}
}
(Not tested, but should work. You can also use sd_image's method to assign an empty url, with a placeholder image to just show the placeholder image. Or just give an empty url string '' without the placeholder image)
Whenever you scroll, the cells are re-used, and the image assigned to the cell reappears because it is still on the cell.
You have to remove those images by using else clause for every if where you are assigning an image to the imageView.
Hope this helps.
You have to write else conditions like Below ..
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! AllPostsOfUserCollectionViewCell
let post = allPostsOfUserArray[collectionView.tag]
if post.imageLinks.count != 0 {
let imageLink = post.imageLinks[indexPath.row]
if imageLink.imageLink != nil {
let url = URL(string: imageLink.imageLink!)
cell.imageOfAnimalInCollectionView.sd_setImage(with: url!, placeholderImage: UIImage(named: "App-Default"),options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in
})
}
else{
cell.imageOfAnimalInCollectionView = "defaultImage"
}
}
else{
cell.imageOfAnimalInCollectionView = "defaultImage"
}
return cell
}
Reason
after dequeueing cell cellectionView reuses the created cell for all next cells so if you not write an else condition or not use prepareForReuse method it will always data of previous cell that is in its cache.
I have the image URL and I want to display that image in UIImageView which is placed in a tableView cell.
I created a custom cell and added an outlet for the imageView.
Since I am loading news the URL changes accordingly.
NOTE: I am using Alamofire to process my HTTP requests.
struct News {
let title: String
let text: String
let link: String
let imgUrl: String
init(dictionary: [String:String]) {
self.title = dictionary["title"] ?? ""
self.text = dictionary["text"] ?? ""
self.link = dictionary["link"] ?? ""
self.imgUrl = dictionary["imgUrl"] ?? ""
}
}
And loading info to my custom cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? newsCellTableViewCell
let news = newsData[indexPath.row]
cell?.headline.text = news.title
cell?.excerpt.text = news.text
cell?.thumbnailImage.text = news.imgUrl
return cell!
}
You can use this code to get image from url and can set a placeholder image as well. for example:-
cell.imageView?.imageFromURL(urlString: "urlString", PlaceHolderImage: UIImage.init(named: "imagename")!)
extension UIImageView {
public func imageFromServerURL(urlString: String, PlaceHolderImage:UIImage) {
if self.image == nil{
self.image = PlaceHolderImage
}
URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error ?? "No Error")
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
self.image = image
})
}).resume()
}}
This becomes quite easy, as you're using Alamofire. Unlike #Mochi's example, this won't block the interface.
Here's an example:
Alamofire.request(news.imgUrl).response { response in
if let data = response.data {
let image = UIImage(data: data)
cell?.thumbnailImage.image = image
} else {
print("Data is nil. I don't know what to do :(")
}
}
*Please note I wasn't able to test this before I answered. You may need to tweak this code a bit.
I used a Kingfisher library
import Kingfisher
tableViewCell class:
class MyCell: UITableViewCell {
#IBOutlet weak var cellImg: UIImageView!
#IBOutlet weak var cellLbl: UILabel!
}
Assign this class to your cell in storyboard
And finally, do this in CellForRowAt
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell")! as! MyCell
let url = URL(string: "https://files.pitchbook.com/website/files/jpg/food_delivery_800.jpg")
cell.cellImg.kf.setImage(with: url)
return cell
}
That's it
Please Use SDWebImage. It's an imageview category that downloads the image in the background without freezing your UI, and also provides caching as well. You can set a placeholder image as well. Placeholders show until your actual image is downloaded. After downloading, the actual image in your cell's Imageview is updated automatically, and you don't need to use any completion handler.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? newsCellTableViewCell
let news = newsData[indexPath.row]
cell?.headline.text = news.title
cell?.excerpt.text = news.text
cell?.thumbnailImage.sd_setImageWithURL(NSURL(string: news.imgUrl), placeholderImage:UIImage(imageNamed:"placeholder.png"))
return cell!
}
My app loads images from a backend and displays them in a UITableViewCell, that contains a UIImageView to display it and some labels and buttons.
I've added the suggested contraints to the UITableViewCell with the 'Reset to suggested contraints' option.
Here's some of the code after retrieving the data:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = PostTableViewCell()
if (self.posts.count == 0) { return cell }
let post = posts[indexPath.row]
// Instancia o reuse identifier
if post["post_image"] != nil {
cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.PostWithImage, for: indexPath) as! PostTableViewCell
} else {
cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.PostWithoutImage, for: indexPath) as! PostTableViewCell
}
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var cell = PostTableViewCell()
cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.PostWithImage) as! PostTableViewCell
return cell.bounds.size.height;
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var cell = PostTableViewCell()
cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.PostWithImage) as! PostTableViewCell
return cell.bounds.size.height;
}
private func configureCell(cell: PostTableViewCell, atIndexPath indexPath: IndexPath) {
cell.queue.cancelAllOperations()
let operation: BlockOperation = BlockOperation()
operation.addExecutionBlock { [weak operation] () -> Void in
DispatchQueue.main.sync(execute: { [weak operation] () -> Void in
if (operation?.isCancelled)! { return }
let post = self.posts[indexPath.row]
cell.accessibilityIdentifier = post.recordID.recordName
guard let postTitle = post["post_title"], let postBody = post["post_body"] else {
return
}
if let asset = post["post_image"] as? CKAsset {
self.imageCache.queryDiskCache(forKey: post.recordID.recordName, done: { (image, cachetype) in
if image != nil {
cell.postImageView.contentMode = .scaleAspectFill
cell.postImageView.autoresizingMask = [.flexibleBottomMargin,
.flexibleHeight,
.flexibleLeftMargin,
.flexibleRightMargin,
.flexibleTopMargin,
.flexibleWidth ];
cell.postImageView.image = image!
} else {
do {
let data = try Data(contentsOf: asset.fileURL)
let image = UIImage(data: data)
cell.postImageView.contentMode = .scaleAspectFill
cell.postImageView.autoresizingMask = [.flexibleBottomMargin,
.flexibleHeight,
.flexibleLeftMargin,
.flexibleRightMargin,
.flexibleTopMargin,
.flexibleWidth ];
cell.postImageView.image = image!
self.imageCache.store(image!, forKey: post.recordID.recordName)
} catch {
print("Error 1001 = \(error.localizedDescription)")
}
}
})
}
cell.titleLabel.text = postTitle as? String
cell.bodyLabel.text = postBody as? String
})
}
cell.queue.addOperation(operation)
}
Here's some prints from the app itself that shows the image overlapping over the labels.
It only overlaps if the image is in portrait mode, if the image was taken in landscape it suits well.
What's the best way to bypass this issue?
You can programmatically tell the image to draw only in the given image area. If your constraints are working properly and it is staying the correct size, the image may just be drawing beyond the View bounds because of the .scaleAscpedtFill setting.
Do this by using .clipToBounds = true.
cell.postImageView.clipToBounds = true
Or, you can set it in interface builder as well, per the image below.
Give that a try and see if that helps?