簡體   English   中英

使用Alamofire和SwiftyJSON將JSON imageURL顯示到UITableView中

[英]Displaying JSON imageURL into UITableView using Alamofire and SwiftyJSON

我目前正在嘗試將JSON數據顯示在我的UITableView上。 我創建了一個單獨的類來處理和聲明從API中提取的數據。 我還創建了一個自定義單元格來顯示數據。 但是我不確定如何顯示API的圖像。 我只使用沒有自定義單元格的標准TableViewController就可以顯示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
}

但是在嘗試創建自定義單元格時, 圖像使用的imageURL的工作方式不同。 其他教程和演示似乎沒有使用AlamofireSwiftyJSON

我確實閱讀了文檔: https//github.com/SwiftyJSON/SwiftyJSON#integration但仍不確定如何解決此問題。 請告訴我你如何在我的桌子上顯示API數據。

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

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
    }

}

視圖控制器

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
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM