【问题标题】:Swift: How to Load JSON in different Table ViewSwift:如何在不同的表视图中加载 JSON
【发布时间】:2021-10-30 05:42:17
【问题描述】:

大家好,我是 Swift 新手,需要帮助。

所以我有三个不同的 JSON 将在不同的时刻显示,第一个 JSON 已经完美加载,但是当我单击该项目以重新加载另一个 JSON 并显示详细信息时,什么都没有出现。

我对细节感到困惑:

需要我为每个 JSON 提供三个不同的表视图吗?还是只有一个就足够了? 当我处理数据 (JSON) 时,我需要使用特定函数来准备新的 JSON,该 JSON 将显示为“准备”?

在我的项目中,我有: 两个视图控制器:ViewController(默认)和 DetailViewController。 在我的 Main.Storyboard 中:Tab Bar Controller --> Navigation --> Table View

第一个View控制器的代码:

import UIKit

class ViewController: UITableViewController {
    var categories = [Category]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let urlString = "https://www.themealdb.com/api/json/v1/1/categories.php"
        
        if let url = URL(string: urlString) {
            if let data = try? Data(contentsOf: url) {
                parse(json: data)
            } else {
                print("error connecting")
            }
        }
    }
    
    func parse(json: Data) {
        let decoder = JSONDecoder()
        print("parse called")
        
        do {
            let jsonCategories = try decoder.decode(Categories.self, from: json)
            
            categories = jsonCategories.categories
            
            tableView.reloadData()
            
        } catch {
            print("error parsin: \(error)")
        }
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return categories.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let category = categories[indexPath.row]
        cell.textLabel?.text = category.idCategory
        cell.detailTextLabel?.text = category.strCategoryDescription
        return cell
    }
    
   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let newViewController = DetailViewController()
        self.navigationController?.pushViewController(newViewController, animated: true)
    }
}


The code of the second view controller:

import UIKit
import WebKit

class DetailViewController: UIViewController {
    var webView: WKWebView!
    var meals = [Meal]()

    override func loadView() {
       webView = WKWebView()
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let urlString = "https://www.themealdb.com/api/json/v1/1/filter.php?c=Beef"
        
        if let url = URL(string: urlString) {
            if let data = try? Data(contentsOf: url) {
                parse(json: data)
            } else {
                print("error connecting")
            }
        }
    }
    func parse(json: Data) {
        let decoder = JSONDecoder()
        print("parse called")
        
        do {
            let jsonMeals = try decoder.decode(Meals.self, from: json)
            
            meals = jsonMeals.meals
            print(String(format:"read %d meals", meals.count))
            
            
            
        } catch {
            print("error parsin: \(error)")
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return meals.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let meal = meals[indexPath.row]
        cell.textLabel?.text = meal.idMeal
        cell.detailTextLabel?.text = meal.strMeal
        return cell
    }
}

【问题讨论】:

  • 您的第二个视图控制器没有表格视图,所以不清楚它应该如何工作?

标签: ios json swift uitableview


【解决方案1】:

DetailViewController上的函数parse(json: Data)没有调用tableView.reloadData()所以新数据无法加载到UITableView

需要我为每个 JSON 提供三个不同的表视图吗?还是只有一个就够了?

如果您正在加载不同的 JSON 文件但希望在同一个视图中显示。你只需要 1 个 UITableViewCell。

当您加载和解码 JSON 时,请考虑将其移至后台队列以避免阻塞主线程。

【讨论】:

  • 非常感谢我添加了 tableView.reloadData() 并且我有这个编译器错误:没有上下文类型就无法解析对成员“reloadData”的引用
  • 因为DetailViewController是一个不同的UIViewController所以你需要为它创建tableView实例,比如ViewController
猜你喜欢
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多