ios - 如何获取json数据并通过segue传递它

标签 ios json swift urlsession

我尝试在 URLSession.dataTask 运行时获取 json 数据以设置 segue 。(每个 json 数据作为发送者)

首先,我创建了自己的类数组productList = [Product]()。 接下来,我调用 getJsonData() 并在其中设置 URLSession.dataTask 方法。所以我得到了解析的json数据。但是,当我尝试从 dataTask finishHandler 保存 json 数据(将每个数据附加到 productList)时,它无法正确保存。(结果 productList[])

我想通过segue传递解析后的json数据。我怎样才能做到这一点?

已编辑--

class MainVC: UITableViewController {

    var productList = [Product]()

    override func viewDidLoad() {
        super.viewDidLoad()

        getJsonData()

    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return productList.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as? ItemCell {
            let product = productList[indexPath.row]

            cell.configureCell(product)

            return cell
        } else {
            return UITableViewCell()
        }
    }


    func getJsonData() {
        let url = URL(string: "http://demo7367352.mockable.io")
        let request = URLRequest(url: url!)
        let defaultSession = URLSession(configuration: URLSessionConfiguration.default)


        let task = defaultSession.dataTask(with: request, completionHandler: { (data, response, error) in

            do {
                guard let data = data, error == nil else {
                    print("network request failed: error = \(error)")
                    return
                }

                guard let rawItem = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
                    print("error trying to convert data to JSON")
                    return
                }


                if let fineItem = rawItem["goods"] as? [[String:Any]] {

                    for item in fineItem {
                        let eachProduct = Product(title: "", price: 0)

                        let title = item["TITLE"]
                        let price = item["PRICE"]
                        let regDate = item["REGDATE"]
                        let description = item["DESCRIPTION"]
                        let iconURL = item["ICON_URL"]
                        let images = item["IMAGES"]


                        if let title = title as? String {
                            eachProduct.title = title
                        }
                        if let price = price as? String {
                            eachProduct.price = Int(price)!
                        }

                        DispatchQueue.main.async(execute: {
                            self.productList.append(eachProduct)
                            self.tableView.reloadData()
                        })
                    }

                }

            } catch  {
                print("error trying to convert data to JSON")
                return
            }

        })
        task.resume()
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToProductDetail" {
            if let controller = segue.destination as? DetailVC, let indexPath = tableView.indexPathForSelectedRow {

            }
        }
    }
 }

现在,我可以从 URLSession DataTask 解析数据。我想实现 tableView 的 segue 以显示详细信息。但是productList是空的。所以我不能将 prepareForSegueproductList[indexPath.row] 一起使用。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToProductDetail" {
        if let controller = segue.destination as? DetailVC, let indexPath = tableView.indexPathForSelectedRow {
            controller.product = productList[indexPath.row] // productList is nil.
        }
    }
}

最佳答案

您需要实现 prepare(for:sender:) 并将数据传递到那里:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let controller = segue.destination as? MySecondViewController, indexPath = tableView.indexPathForSelectedRow {
        controller.product = productList[indexPath.row]
    }
}

确切的语法会有所不同(目标 View Controller 的类名是什么),您必须声明 product目的地的属性(property),以及目的地的viewDidLoad需要使用该属性,但希望它说明了基本思想。

<小时/>

一些额外的观察结果:

  1. 我建议您检查 rawItem并确保它是一个字典,其中有一个名为 goods 的键并且与该键关联的值实际上是一个字典数组。如果没有看到您的 JSON,就不可能说出到底出了什么问题。

    另外,请考虑:

    if let fineItem = rawItem["goods"] as? [[String:Any]] {
        ...
    }
    

    如果失败,你永远不会知道。我可能会建议:

    guard let fineItem = rawItem["goods"] as? [[String:Any]] else {
        print("goods not found or wrong type")
        return
    }
    ...
    
  2. 顺便说一句,与您手头的问题无关,变异有点危险 productList直接在数据任务的完成处理程序中。不要异步改变一个线程中从另一线程读取的数组。数组不是线程安全的。数据任务完成处理程序应该构建一个本地数组,并且只有当它完成时,在将重新加载分派(dispatch)到主队列的位置,才应该插入代码来替换 productList在重新加载表之前使用本地数组。

  3. 此外,您当前正在调用 reloadData在解析循环内。您通常会在解析循环结束时调用它。现在,如果您的数据集有 100 行,您将重新加载表格 100 次。

  4. data! 的引用有点危险。如果您没有互联网连接,data将是nil你的代码将会崩溃。我建议:

    guard let data = data, error == nil else {
        print("network request failed: error = \(error)")
        return
    }
    

    然后你可以替换 data!引用data .

关于ios - 如何获取json数据并通过segue传递它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43029851/

相关文章:

ios - 执行自定义 View Controller 时出现问题关闭动画

ios 通用链接 - 来自多个域

javascript - 如何在不刷新页面的情况下自动刷新多个php变量?我只能办理一台atm

javascript - 将对象数组转换为数组数组

ios - UIImagePickerController 关闭后,UICollectionView 不会重新加载数据()

java - 无法为 map 设置正确的 JSON 格式

swift - RxSwift 和LatestFrom 奇怪的行为

ios - 将数据从 CollectionView 传递到 TabBarController,而不是在 Swift 中传递给他的 child

swift - 从 NSPasteboard 检索时,backgroundColor 属性丢失

ios - 在 UISegmentedControl 中控制色调颜色