簡體   English   中英

如何正確管理JSON提供的圖像

[英]How should I manage correctly images provided by JSON

我正在嘗試解析由我的App上下載的JSON提供的所有圖像。 因此,我聽說過許多正確執行此操作的方法。 我應該使用哪個API在我的應用程序上管理圖像? 我應該如何做,我可以舉個例子嗎?

我還想正確處理以下之間的延遲:

運行應用程序->加載數據->填充UI元素

我應該怎么做才能最大程度地減少這種延遲,我認為專業的應用程序應該花這么長時間來加載所有組件。

那就是我將用圖像填充UITableView的部分。

var arrCerveja = [Cerveja]()

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    //TableView DataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrCerveja.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellID") as! TableViewCell

        let model = arrCerveja[indexPath.row]

            cell.labelName.text = model.name
            cell.labelDetail.text = "\(model.abv)"
            cell. imageViewCell.image = ???? //How should I do that? 
        return cell
    }
    //TableView Delegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }



    override func viewDidLoad() {
        super.viewDidLoad()
        getApiData { (cerveja) in
           arrCerveja = cerveja
           self.tableView.reloadData()
        }

    }

模型文件夾:

import Foundation
struct Cerveja:Decodable{
    let name:String
    let abv:Double
    let image_url:String
}

網絡文件夾:

import Alamofire


func getApiData(completion: @escaping ([Cerveja]) -> ()){
    guard let urlString = URL(string: "https://api.punkapi.com/v2/beers") else {
        print("URL Error")
        return
    }
    Alamofire.request(urlString).responseJSON { response in

        if response.data == response.data{
            do{
                let decoder = try JSONDecoder().decode([Cerveja].self, from: response.data!)

                completion(decoder)
            }catch{
        print(error)
            }
        }else{print("API Response is Empty")}

        }
}

您可以做的是緩存下載的圖像,有許多庫可以幫助您完成此任務,以下是其中一些列表:

Kingfisher是一個很好的工具,它還允許您下載圖像並向您說明如何使用帶表視圖的庫。 緩存圖像還將減少下次打開應用程序時的加載時間。 您還可以使用此庫在加載期間向用戶顯示用戶友好的加載。

暫無
暫無

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

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