/Example/KFSwiftImageLoader/View Controllers/MainViewController.swift

https://github.com/kiavashfaisali/KFSwiftImageLoader · Swift · 119 lines · 82 code · 23 blank · 14 comment · 18 complexity · 27b3074adf41d072dbac355d4dde8462 MD5 · raw file

  1. //
  2. // Created by Kiavash Faisali on 2015-03-17.
  3. // Copyright (c) 2015 Kiavash Faisali. All rights reserved.
  4. //
  5. import UIKit
  6. import os
  7. import KFSwiftImageLoader
  8. final class MainViewController: UIViewController {
  9. // MARK: - Properties
  10. @IBOutlet weak var imagesTableView: UITableView!
  11. var imageURLStrings = [String]()
  12. // MARK: - Memory Warning
  13. override func didReceiveMemoryWarning() {
  14. super.didReceiveMemoryWarning()
  15. }
  16. // MARK: - View Lifecycle
  17. override func viewDidLoad() {
  18. super.viewDidLoad()
  19. loadDuckDuckGoResults()
  20. }
  21. // MARK: - Miscellaneous Methods
  22. func loadDuckDuckGoResults() {
  23. let url = URL(string: "https://api.duckduckgo.com/?q=simpsons+characters&format=json")!
  24. let request = URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 60.0)
  25. let dataTask = URLSession.shared.dataTask(with: request) {
  26. (data, _, error) in
  27. guard let data = data, error == nil else {
  28. os_log("Error retrieving a response from the DuckDuckGo API: %{public}@", type: .error, error!.localizedDescription)
  29. return
  30. }
  31. DispatchQueue.main.async {
  32. do {
  33. if let jsonDict = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject],
  34. let relatedTopics = jsonDict["RelatedTopics"] as? [[String: AnyObject]]
  35. {
  36. for relatedTopic in relatedTopics {
  37. if let imageURLString = relatedTopic["Icon"]?["URL"] as? String, imageURLString != "" {
  38. for _ in 1...3 {
  39. self.imageURLStrings.append(imageURLString)
  40. }
  41. }
  42. }
  43. if self.imageURLStrings.count > 0 {
  44. // Comment to not randomize the image ordering.
  45. self.randomizeImages()
  46. self.imagesTableView.reloadData()
  47. }
  48. }
  49. }
  50. catch {
  51. os_log("Error when parsing the response JSON: %{public}@", type: .error, error.localizedDescription)
  52. }
  53. }
  54. }
  55. dataTask.resume()
  56. }
  57. func randomizeImages() {
  58. for i in 0..<self.imageURLStrings.count {
  59. let randomIndex = Int(arc4random()) % self.imageURLStrings.count
  60. self.imageURLStrings.swapAt(i, randomIndex)
  61. }
  62. }
  63. }
  64. // MARK: - UITableViewDataSource Protocol
  65. extension MainViewController: UITableViewDataSource {
  66. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  67. return self.imageURLStrings.count
  68. }
  69. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  70. // Even indices should contain imageview cells.
  71. if (indexPath.row % 2) == 0 {
  72. let identifier = String(describing: ImageTableViewCell.self)
  73. let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! ImageTableViewCell
  74. cell.featuredImageView.loadImage(urlString: self.imageURLStrings[indexPath.row], placeholder: UIImage(named: "KiavashFaisali")) {
  75. (success, error) in
  76. guard error == nil else {
  77. os_log("Error occurred when loading the image: %{public}@", type: .error, error!.localizedDescription)
  78. return
  79. }
  80. if !success {
  81. os_log("Image could not be loaded from the provided URL, or the index paths didn't match due to fast scrolling, which would've placed the image in an incorrect cell.", type: .info)
  82. }
  83. }
  84. return cell
  85. }
  86. // Odd indices should contain button cells.
  87. else {
  88. let identifier = String(describing: ButtonImageTableViewCell.self)
  89. let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! ButtonImageTableViewCell
  90. // Notice that the completion closure can be ommitted, since it defaults to nil. The `controlState` and `isBackground` parameters can also be ommitted, as they default to `.normal` and `false`, respectively.
  91. // Please read the documentation for more information.
  92. cell.featuredButton.loadImage(urlString: self.imageURLStrings[indexPath.row], placeholder: UIImage(named: "KiavashFaisali"), controlState: .normal, isBackground: false)
  93. return cell
  94. }
  95. }
  96. }