chen shiyi
chen shiyi

Reputation: 9

IndexPath does not point to correct cell in swift

I an a swift beginner, just start to try to delete data from a python flask I built. However the indexpath command always points to the next line deleted in the table view:

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete {
        models?.remove(at: indexPath.row)

        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

        let cell = tableView.cellForRow(at: indexPath) as? TableViewCell
        let dateid = cell?.dateLabel.text   
        print(dateid as Any)
        self.tableView.reloadData()
        let model = models![(indexPath.row)]
        let id = (model.healthdataid)-1
        guard let url = URL(string:"http://localhost:1282/healthdata/\(String(describing: id))") else {
            print("ERROR")

            return
        }
        var urlRequest = URLRequest(url:url)
        urlRequest.httpMethod = "DELETE"
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration:config)
        let task = session.dataTask(with: urlRequest, completionHandler:{
            (data:Data?, response: URLResponse?,error: Error?) in


        })
        task.resume()


        }
}        

And this is data i am trying to deal with

data = [
 {'healthdataid' : 1 ,
 'date':'2017-01-02',
 'value' : 56},

{'healthdataid': 2 ,
'date':'2017-01-03',
'value' : 54},

{'healthdataid' : 3 ,
'date':'2017-01-04',
'value' : 100},

{'healthdataid' : 4 ,
'date' : '2017-01-04',
'value' : 1}

Upvotes: 1

Views: 53

Answers (1)

AamirR
AamirR

Reputation: 12198

I will address few things that concerns me about your code:

  1. You are deleting the array element with this line models?.remove(at: indexPath.row), and later in the code you are trying to access the same element.

  2. Don't remove item before success from API

  3. Check if API responded with success or there any error

  4. It is not necessary to call tableView.deleteRows when you calling tableView.reloadData

Try this, it fixes these issues:

guard
    editingStyle == UITableViewCellEditingStyle.delete,
    let id = models?[indexPath.row].healthdataid,
    let url = URL(string:"http://localhost:1282/healthdata/\(id)")
else {
    return
}

var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "DELETE"
let config = URLSessionConfiguration.default
let session = URLSession(configuration:config)
let task = session.dataTask(with: urlRequest) { (data: Data?, response: URLResponse?, error: Error?) in

    guard error == nil else {
        print(error!.localizedDescription)
        return
    }

    if let index = models?.index(where: { $0.healthdataid == id }) {
        models!.remove(at: index)
        self.tableView.reloadData()
    }

})
task.resume()

// For Test Purpose
let cell = tableView.cellForRow(at: indexPath) as? TableViewCell
print(cell?.dateLabel.text ?? "")

Upvotes: 1

Related Questions