I did the following code and is working pretty decent but I am not finding the way to reload the tableView after each image is downloaded. I am using Alamofire to download all the content list data and images.
How I can access to tableView from extension?
If someone can give me any advice I will appreciate so much :)
import UIKit
import Alamofire
import AlamofireImage
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var jsonArray: NSArray?
var nameArray: Array<String> = []
var imageURLArray: Array<String> = []
override func viewDidLoad() {
super.viewDidLoad()
downloadDataFromAPI()
}
func downloadDataFromAPI(){
Alamofire.request("http://private-135b4e-solamente.apiary-mock.com/pokemonList") .responseJSON { response in
if let JSON = response.result.value{
self.jsonArray = JSON as? NSArray
for item in self.jsonArray! as! [NSDictionary]{
//5.
let name = item["name"] as? String
let imageURL = item["image"] as? String
self.nameArray.append((name)!)
self.imageURLArray.append((imageURL)!)
}
print(self.nameArray)
self.tableView.reloadData()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.nameArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell:UITableViewCell=UITableViewCell(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: "mycell")
cell.textLabel?.text = nameArray[indexPath.row]
cell.imageView!.downloaded(from: imageURLArray[indexPath.row])
return cell
}
}
extension UIImageView {
func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) { // for swift 4.2 syntax just use ===> mode: UIView.ContentMode
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloaded(from: url, contentMode: mode)
}
}