【问题标题】:Trying to parse JSON data to put in another JSON url to parse more data尝试解析 JSON 数据以放入另一个 JSON url 以解析更多数据
【发布时间】:2019-06-06 22:55:52
【问题描述】:

所以情况是这样,我试图解析来自链接 1 的 JSON 数据,并将其放在一个 url 中以解析来自链接 2 的 JSON 数据。我为此创建了两个结构。第一个结构是我的收集(我必须使用我的 id 来解析第二个链接中的其他 JSON)

struct Collects: Codable {
    let collects: [Collect]
}

struct Collect: Codable {
    let productID: Int

    enum CodingKeys: String, CodingKey {
        case productID = "product_id"
    }
}

我的第二个包含产品的结构(将从第二个链接解析

struct Products: Codable {
    let products: [Product]
}

struct Product: Codable {
    let title: String
    enum CodingKeys: String, CodingKey {
        case title
    }
}

Product 结构中的标题是产品的名称。在我的视图控制器中,我有以下两个用于获取 JSON 的函数:

func fetchJSON(url: String, completion: @escaping (Collects?, Error?) -> Void) {
    guard let url = URL(string: url) else { return }

let session = URLSession.shared
let dataTask = session.dataTask(with: url) { (data, response, error) in
    if let error = error {
        completion(nil, error)
        print("Unable to fetch data", error)
    }
    guard let data = data else { return }
    do {
        let response = try JSONDecoder().decode(Collects.self, from: data)
        DispatchQueue.main.async {
            completion(response, nil)
        }
    } catch let jsonError{
        print("Unable to decode: ", jsonError)
    }
}
dataTask.resume()
}

func fetchProducts(url: String, completion: @escaping (Products?, Error?) -> Void) {
    guard let url = URL(string: url) else { return }

let session = URLSession.shared
let dataTask = session.dataTask(with: url) { (data, response, error) in
    if let error = error {
        completion(nil, error)
        print("Unable to fetch data", error)
    }
    guard let data = data else { return }
    do {
        let response = try JSONDecoder().decode(Products.self, from: data)
        DispatchQueue.main.async {
            completion(response, nil)
        }
    } catch let jsonError{
        print("Unable to decode: ", jsonError)
    }
}
dataTask.resume()
 }

第一个用于解析 id,第二个用于解析产品。在我的 viewDidLoad 中,我使用此信息来获取数据并对其进行设置,以便可以将产品放入集合视图中。

在我的 viewDidLoad 中,我有以下

let jsonURL = "https://xxxxxxxxxxxxx"


//We need to first fetch the collects
fetchJSON(url: jsonURL) { (response, error) in
    guard let item = response?.collects else { return }
    self.collects = item
    for i in self.collects {
        //This will put all the id's together
        self.collectionCollects.append(",")
        self.collectionCollects.append(String(i.productID))
    }
    //This will remove the first comma in the string
    self.collectionCollects.remove(at: self.collectionCollects.startIndex)

    //This is the productURL that we will use to retrieve the products and put them in the collectionView
    let productURL = "https://xxxxxxxxxxxxx\(self.collectionCollects)&page"

    self.fetchProducts(url: productURL, completion: { (response, error) in
        guard let item = response?.products else {return}
        self.products = item
        self.collectionView.reloadData()
        //The products get printed here
        print(self.products)
    }
  )
}

稍微解释一下,JSONUrl 是 JSON 数据的第一个 url,它被传递到函数中以获取信息。在第一个 for 循环中,我正在做的是获取 id 并将它们放在一个字符串中并用逗号分隔它们,然后删除第一个逗号。之后,我调用第二个 JSON 函数使用新 URL 来获取第二个 URL 的产品。在语句“print(self.products)”中,我得到了我期望的产品列表,即使我在 self.fetchProducts 中执行一个 for 循环来遍历并打印出产品,我也会得到预期的结果。但是,当我尝试使用数据设置我的集合视图时,它只是一个没有信息的白屏。我认为问题在于我如何设置而不是我的单元格的配置。

我忘记提及的一件事是,在我的视图控制器中,我有以下数组:

var collects = [Collect]()
var collectionCollects = ""
//This will have the products
var products = [Product]()

我真的被困住了,我不确定是最好在一个视图控制器中完成所有这些操作还是将其拆分,但它必须是一个视图。

【问题讨论】:

    标签: json swift urlsession


    【解决方案1】:

    您的问题是关于集合视图。我建议看一下here。如果您在迭代时得到正确的响应,那么它设置的集合视图就是您的问题。

    【讨论】:

    • 所以我能够到达某个地方,我忘记在我的视图中添加“self.view.addSubview(collectionView)”确实加载并为collectionView提供了一些约束,但现在我得到一个转换错误“无法将'OmarJSON.CustomCollectionViewCell'(0x104b7e2d0)类型的值转换为'OmarJSON.ProductCollectionViewCell'(0x104b7e240)。2019-01-12 00:00:31.587722-0500 OmarJSON [24971:5540997] 无法转换类型' OmarJSON.CustomCollectionViewCell' (0x104b7e2d0) 到 'OmarJSON.ProductCollectionViewCell' (0x104b7e240)。"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多