首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Alamofire和imageURL将JSON imageURL显示到UITableView中

使用Alamofire和imageURL将JSON imageURL显示到UITableView中
EN

Stack Overflow用户
提问于 2017-02-18 22:30:33
回答 1查看 674关注 0票数 0

我目前正在尝试将JSON数据显示到我的UITableView上。我创建了一个单独的类,它处理并声明从API中提取的数据。我还创建了一个自定义单元格来显示数据。但是,我不知道如何显示API的图像。我只使用一个没有自定义单元格的标准TableViewController来显示API的标题:

代码语言:javascript
复制
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
}

但是,在尝试创建自定义单元时,映像使用的是一个工作方式不同的imageURL。其他教程和演示似乎没有使用、Alamofire、SwiftyJSON

我确实读过文档:https://github.com/SwiftyJSON/SwiftyJSON#integration,但仍然不知道如何解决这个问题。请告诉我如何将API数据显示在我的表上。

班级

代码语言:javascript
复制
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

        }


    }

CustomCell

代码语言:javascript
复制
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

代码语言:javascript
复制
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
}

(预先多谢!)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-20 05:53:42

为此,您必须将Imageview的扩展作为

代码语言:javascript
复制
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方法编写为

代码语言:javascript
复制
  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
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42321431

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档