我是一个快速的初学者,刚刚开始尝试从我构建的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}
答案 0 :(得分:1)
我将解决与您有关的代码的一些问题:
您正在使用此行models?.remove(at: indexPath.row)
删除数组元素,稍后在您尝试访问相同元素的代码中删除。
请勿在API
检查API是否成功响应或有任何错误
致电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 ?? "")