我是一个快速的初学者,刚开始尝试从我建立的python烧瓶中删除数据。但是,indexpath命令始终指向表视图中删除的下一行:
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()
}
}
这是我想要处理的数据
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}
我将解决一些与我有关的代码:
models?.remove(at: indexPath.row)
删除数组元素,稍后在您尝试访问相同元素的代码中。tableView.deleteRows
时,没有必要打电话给tableView.reloadData
试试这个,它修复了这些问题:
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 ?? "")