我有一个填充了JSON数据的表视图。到现在为止还挺好!但是我希望只有当json中的id等于特定的内容时才会填充我的表视图(行数)。就我而言: " ttc_proposta_tipo_id" =" e0eb2736-433e-475e-876d-bcc6b460e1e3"
如果没有,返回0
我不知道我是否足够清楚,这是我的第一个问题。
感谢名单
我的代码:
class NavigationTest: UIViewController{
@IBOutlet weak var btnAddProposta: UIBarButtonItem!
@IBOutlet var tableView: UITableView!
let searchController = UISearchController(searchResultsController: nil)
var propostas = [Proposta]()
private var refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
setupSideMenu()
fetchJSON()
self.tableView.register(CustomCell.self, forCellReuseIdentifier: "cell")
}
struct Proposta: Decodable {
let TtcProposta: TtcProposta
let TtcBasaFinalidade: TtcBasaFinalidade
let TtcCar: [TtcCar]?
enum CodingKeys: String, CodingKey {
case TtcProposta = "TtcProposta"
case TtcBasaFinalidade = "TtcBasaFinalidade"
case TtcCar = "TtcCar"
}
}
struct TtcProposta: Decodable {
let id: String?
let user_id: Int?
let versao: String?
let status_processo: String?
let finalidade: String?
let valor_proposta: String?
let detalhes_json: detalhes_json?
let ativo: Bool?
let modified: String?
let inst_financeira_id: String?
let ttc_basa_finalidade_id: String?
let seq: Int?
let ttc_proposta_tipo_id: String?
let data_envio: String?
let liberado_banco: String?
let numero_fip: String?
let numeroProtocolo: String?
let created: String?
}
fileprivate func fetchJSON() {
let urlPath = "http://credito-homologacao.branch.terras.agr.br/ttc/ttc_propostas/get_by_user"
let url = NSURL(string: urlPath)
let session = URLSession.shared
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "GET" // make it post if you want
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
// Swift 4.1
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.propostas = try decoder.decode([Proposta].self, from: data)
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
})
task.resume()
}
延伸:
extension NavigationTest: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//THIS IS WHAT TRIED AND IT DIDNT WORK
//ERROR:Value of type '[NavigationTest.Proposta]' has no member 'TtcProposta'
if propostas.TtcProposta.ttc_proposta_tipo_id == "e0eb2736-433e-475e-876d-bcc6b460e1e3" {
return propostas.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
let proposta = propostas[indexPath.row]
cell.delegate = self
cell.numeroProposta.text = proposta.TtcProposta.numeroProtocolo
cell.proponenteNome.text = proposta.TtcProposta.finalidade
return cell
}
答案 0 :(得分:1)
不要在numberOfRowsInSection
中执行此操作,这是错误的地方,请在解码JSON后立即查看。
创建一个包含所有id
值的数组,并检查它是否包含给定的id
。
如果检查成功,则分配result
,否则分配一个空数组。
let result = try decoder.decode([Proposta].self, from: data)
let ids = result.compactMap { $0.TtcProposta.id }
if ids.contains("e0eb2736-433e-475e-876d-bcc6b460e1e3") {
self.propostas = result
} else {
self.propostas = []
}
编辑:如果您想过滤给定id
的所有元素,请写
let result = try decoder.decode([Proposta].self, from: data)
self.propostas = result.filter { $0.TtcProposta.id == "e0eb2736-433e-475e-876d-bcc6b460e1e3" }
并照常返回numberOfRowsInSection
return propostas.count
附注:您为什么设置选项.convertFromSnakeCase
但不使用 camelCased 属性名称?
答案 1 :(得分:0)
使用过滤器是最简单的。
let decoder = JSONDecoder()
// Swift 4.1
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.propostas = try decoder.decode([Proposta].self, from: data).filter { return $0.ttc_proposta_tipo_id == "e0eb2736-433e-475e-876d-bcc6b460e1e3" }