I am fetching JSON data from my website to a table view with image view. Data is loading fast except the images are very slow in loading and makes the tableview not responding.
Here is my cellForRowAt
code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let customCell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
//let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
let item = data[indexPath.row]
customCell.AdTitle?.text = item["title"].string
customCell.AdDate?.text = item["time"].string
if let imageUrl = item["document"].string {
AF.request("https://mysite.co/uploads/" + imageUrl).responseImage { response in
if case .success( _) = response.result {
let url = NSURL(string:("https://mysite.co/uploads/" + imageUrl))
let imagedata = NSData.init(contentsOf: url! as URL)
if imagedata != nil {
customCell.AdImage.image = UIImage(data:imagedata! as Data)
}
}
}
}
return customCell
}
You can simply load your images with advance cache system through SDWebImage like below:
let imageURL = URL(string: "youRemoteImageURL") //Image URL
yourImageView.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "placeholder.png"))
Your tableViewCell will look like below:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let customCell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
let item = data[indexPath.row]
customCell.AdTitle?.text = item["title"].string
customCell.AdDate?.text = item["time"].string
let imageUrl = item["document"].string
let url = NSURL(string:("https://mysite.co/uploads/" + imageUrl))
customCell.AdImage.sd_setImage(with: url, placeholderImage: UIImage(named: "placeholder.png"))
return customCell
}