如何使用带有JSONDecoder的自定义完成块来解析嵌套的JSON?

时间:2019-07-09 06:48:13

标签: ios json swift

我有嵌套的json对象,需要解析并填写json中带有imageUrls的collectionViewCell i need to iterate overe list.recommendBannerImages and save it in external var so that i can use it into my collectionViewCells

1 个答案:

答案 0 :(得分:0)

首先,您为此编写一个函数,并假定此函数名称fetchData和您的数据模型应符合Codable协议。

func fetchData(url: String, completion: @escaping(Result<[DataModel], Error>)->()){
guard let url = URL(string: url) else { return }
    URLSession.shared.dataTask(with: url){(data, response, error) in
        if error != nil{
            completion(.failure(error!))
            print(error!)
        } else{
            guard let _ = response as? HTTPURLResponse, let jsonData = data  else { return }
            let yourDataModel = try? JSONDecoder().decode([DataModel].self, from: jsonData)
            guard let dataModels = mainPageContentData else { return } //dataModels is array of DataModel
            completion(.success(dataModels)) // And we send this array to completion blocks
        }
        }.resume()
}

您应该像这样使用此功能

        fetchData { (result) in //Trailing closure syntax
        switch result {
        case .failure(let error):
            print(error)
        case .success(let datas):
            for data in datas{
              print(data)
              }
         }
     }