下载每个图像后重新加载tableview

时间:2019-07-29 19:12:21

标签: ios swift uitableview alamofire

我执行了以下代码,并且工作得相当不错,但是在找到每个图像后,我没有找到重新加载tableView的方法。我正在使用Alamofire下载所有内容列表数据和图像。

如何从扩展名访问tableView?

如果有人可以给我任何建议,我将不胜感激:)

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)
    }
}

1 个答案:

答案 0 :(得分:2)

下载每个图像后,您无需重新加载表格视图。您需要在此函数func downloaded的回调中返回图像。您可以在Objective-c中找到类似的答案。

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling