Guest User

Swift Async Image Download

a guest
Feb 25th, 2017
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.22 KB | None | 0 0
  1. import UIKit
  2.  
  3. /* Reusable ID = "customCell" */
  4. class CustomTableViewCell: UITableViewCell {
  5.     var imageUrl: String!
  6.     @IBOutlet weak var imageView: UIImageView!
  7.     @IBOutlet weak var name: UILabel!
  8.     .
  9.     .
  10.     .
  11. }
  12.  
  13. class UIViewController: UITableDelegate, UITableDataSource {
  14.    
  15.     var people = [Person]() // populated at some point with person.name and person.imageUrl?
  16.     .
  17.     .
  18.     .
  19.     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  20.         if let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as? CustomTableViewCell {
  21.             if let person = people[indexPath.row] {
  22.                 cell.name = person.name
  23.                 if let imageUrl = person.imageUrl {
  24.                     cell.imageUrl = imageUrl
  25.                     // Download image from URL asynchronously
  26.                     URLSession.shared.dataTask(with: imageUrl) { data, response, error in
  27.                         guard let data = data, error == nil else { return }
  28.                         DispatchQueue.main.async() { () -> Void in
  29.                             if cell.imageUrl == imageUrl { // If cell url still matches downloaded image url, set to imageView. Otherwise discard (or cache)
  30.                                 self.imageView.image = UIImage(data: data)
  31.                             }
  32.                         }
  33.                     }.resume()
  34.                 }
  35.             }
  36.         }
  37.     }
  38. }
Add Comment
Please, Sign In to add comment