使用 Alamofire 和 Swifty JSON 将 imageURL 显示到 UITableViewJSON

Displaying JSON imageURL into UITableView using Alamofire and SwiftyJSON

我目前正在尝试将 JSON 数据显示到我的 UITableView 上。我创建了一个单独的 class 来处理和声明从 API 中提取的数据。我还创建了一个自定义单元格来显示数据。但是我不确定如何显示 API 的图像。我能够仅使用没有自定义单元格的标准表 ViewController 来显示 API 的标题:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "recipeCell", for: indexPath)

    cell.textLabel?.text = recipes = [indexPath.row].title

    return cell
}

但是在尝试创建自定义单元格时,image 使用的 imageURL 的工作方式不同。其他教程和演示似乎没有使用 AlamofireSwiftyJSON

我确实阅读了文档:https://github.com/SwiftyJSON/SwiftyJSON#integration 但仍然不确定如何解决此问题。请告诉我如何让 API 数据显示在我的 table.

Class

import Foundation
import SwiftyJSON

    class Recipe {

        var title: String!
        var image: URL?


        init(json: JSON) {
            self.title = json["title"].stringValue
            self.image = json["image"].url

        }


    }

自定义单元格

import UIKit

class RecipeCell: UITableViewCell {


    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var imgView: UIImageView?



    override func awakeFromNib() {
        super.awakeFromNib()

        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

ViewController

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.
    Alamofire.request(searchURL, method: .get, parameters: params, encoding: URLEncoding.default, headers: headers).response { [unowned self] response in
        guard let data = response.data else { return }
        let json = JSON(data: data)

        for recipe in json.arrayValue {
            let newRecipe = Recipe(json: recipe)
            self.recipes.append(newRecipe)


        }

        for recipe in self.recipes {
            print(recipe.title)
            print(recipe.image)

        }



    }


}

// Display JSON Data into the tableView

 func tableView( _ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return recipes.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "recipeCell", for: indexPath)

    // What to write here?

    return cell
}

提前致谢! :)

为此,您必须将 Imageview 扩展为

extension UIImageView {
    func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        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() { () -> Void in
                self.image = image
            }
            }.resume()
    }
    func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        downloadedFrom(url: url, contentMode: mode)
    }
 }

那么你必须将 cellForRowAt 方法写成

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "recipeCell", for: indexPath)
    let recipe = recipes[indexPath.row]
    let imagePath = recipe.image
    cell.titleLabel.text = recipe.title
    cell. imgView.downloadedFrom(link: imagePath)

        return cell
    }