Search code examples
jsonswiftbuttontableview

Unable to delete tableview row with button and JSON data in Swift


I am getting JSON data successful and when i click cancelTapped button.. then.. service is deleted from JSON but in tableview row is still showing, why

after cancel the service i need not to show the row

code: here cancelid is which service i need to delete from tableview that sevice id

var cancelid: String?

override func viewWillAppear(_ animated: Bool) {
tableView.reloadData()
}
func deleteServiceCall(){

print("cancel id : \(cancelid)")

let param = ["wishlist_id" : cancelid]
APIReqeustManager.serviceCall(param: param, method: .post, vc: self, url: CommonUrl.delete_request, isTokenNeeded: true, isErrorAlertNeeded: true, isSuccessAlertNeeded: false) { [weak self] (resp) in
    if let code = ((resp.dict?["result"] as? [String : Any])){
        let success = code["status"] as? [String : Any]
        if success == "Success"{
            DispatchQueue.main.async {
                self?.tableView.reloadData()
            }
        }
    }
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return wishlistData?.result?.wishlist?.count ?? 0
}

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "fundTableViewCell", for: indexPath) as! FundTableViewCell

let indexData = wishlistData?.result?.wishlist?[indexPath.row]

cancelid = String(indexData?.id ?? 0)
cell.cancelBtn.tag = indexPath.row
cell.cancelBtn.addTarget(self, action: #selector(cancelTapped(sender:)), for: UIControl.Event.touchUpInside)

return cell

}


@objc func cancelTapped(sender: UIButton) {

self.showTwoButtonAlertWithLeftAction(title: "WithDraw", buttonTitleLeft: "Yes", buttonTitleRight: "Cancel", message: "Do you want to remove this withdrawel Request!?") {
    self.deleteServiceCall()
}
}

Solution

  • [String : Any] compared to a String always fails.

    The value of status is most likely a String.

    And you have to remove the item also from the data source array.

    if let code = resp.dict?["result"] as? [String : Any], 
        let success = code["status"] as? String, success == "Success" {
            DispatchQueue.main.async {
                if let index = self?.wishlistData?.result?.wishlist?.firstIndex(of: {$0.id == cancelid}) {
                   self?.wishlistData?.result?.wishlist?.remove(at: index)
                   self?.tableView.removeRows(at: [IndexPath(row: index, section: 0)], with: .fade)
                }
            }
    }
    

    Note: You should declare the data source array as non-optional empty array to get rid of all those optionals.