首页 > 解决方案 > iOS 多个 JSON 文件数据通过 Swift 中的 segue 传输

问题描述

我正在尝试制作一个国家天气预报应用程序,我有 vc1 和 vc2。

每个国家都存在vc2中要解析的json文件,当点击vc1的表格视图单元格时,我们尝试在vc2中实现解析国家的json文件。

但是,我不知道如何通过 segue 将 JSON 文件名从 vc1 传递到 vc2。

使用 segue 从 vc1 传递到 vc2 时,变量为 nil。有什么解决办法吗?

谢谢阅读。

vc1

class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    var countries = [Countries]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        
        let jsonDecoder = JSONDecoder()
        guard let dataAsset = NSDataAsset(name: "countries")
            else {
                return
        }
        do {
            countries = try jsonDecoder.decode([Countries].self, from: dataAsset.data)
        } catch {
            print(error.localizedDescription)
        }
        tableView.reloadData()
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return countries.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath)
        let country: Countries = countries[indexPath.row]
        cell.imageView?.image = UIImage(named: "flag_" + country.asset_name)
        cell.textLabel?.text = country.korean_name
        return cell
    }
    
    // Data Transfer
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let nextViewController: SecondViewController = segue.destination as? SecondViewController else {
            return
        }
        guard let cell: UITableViewCell = sender as? UITableViewCell else {
            return
        }
        func name(indexPath: IndexPath) {
            let country: Countries = countries[indexPath.row]
            nextViewController.title = cell.textLabel?.text
            nextViewController.secondAssetName = country.asset_name
        }
        
    }
}

vc2

class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    
    var weathers = [Weather]()
    var secondAssetName: String?
        
    @IBOutlet weak var tableView: UITableView!
    
        override func viewDidLoad() {
        super.viewDidLoad()
            
            self.tableView.delegate = self
            self.tableView.dataSource = self
        
            
        let jsonDecoder = JSONDecoder()
            guard let dataAsset = NSDataAsset(name: secondAssetName ?? " ") else {
            return
        }
        do {
            weathers = try jsonDecoder.decode([Weather].self, from: dataAsset.data)
        } catch {
            print(error.localizedDescription)
        }
        tableView.reloadData()
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return weathers.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
        let weather: Weather = weathers[indexPath.row]
        
        switch weather.state {
            case 10:
                cell.cellImageView?.image = UIImage(named: "sunny.png")
            case 11:
                cell.cellImageView?.image = UIImage(named: "cloudy.png")
            case 12:
                cell.cellImageView?.image = UIImage(named: "rainy.png")
            case 13:
                cell.cellImageView?.image = UIImage(named: "snowy.png")
            default:
                return cell
        }
        cell.cityNameLabel.text = weather.city_name
        cell.temperatureLabel.text = String(weather.celsius)
        cell.rainfallProbabilityLabel.text = String(weather.rainfall_probability)
        return cell
    }
}

在此处输入图像描述

标签: iosjsonswifttableviewdata-transfer

解决方案


在 VC1 中,您何时导航到 VC2?如果您在情节提要中连接了 VC1 和 VC2,请将其删除。

当用户选择一个单元格时,您需要调用“performSegueWithIdentifier”方法。

为此,您需要实现 tableview 的didSelectRowAtIndexPath. 在这个方法中,需要调用该performSegueWithIdentier方法导航到vc2。

还,

在准备 segue 方法中,您有此代码。

func name(indexPath: IndexPath) {
        let country: Countries = countries[indexPath.row]
        nextViewController.title = cell.textLabel?.text
        nextViewController.secondAssetName = country.asset_name
    }

为什么你有它的功能?你不是在这里调用名称函数吗?

您可以将以下代码移到name(index path:)函数之外。

像这样:

    // Data Transfer
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let nextViewController: SecondViewController = segue.destination as? SecondViewController else {
        return
    }
    guard let cell: UITableViewCell = sender as? UITableViewCell else {
        return
    }

    let country: Countries = countries[indexPath.row]
    nextViewController.title = cell.textLabel?.text
    nextViewController.secondAssetName = country.asset_name
    
}

推荐阅读