kerkerj
今天要處理刪除
其實超簡單的
只是想偷懶一下 XD
一樣將下列程式碼新增到 RestApi class:
func deleteTodoList(completionHandler: ((NSDictionary!, NSError!) -> Void)!, todoId: String) {
var session = NSURLSession.sharedSession()
var request = NSMutableURLRequest(URL: NSURL(string: "http://192.168.1.158:3000/user/kerkerj/todos/\(todoId)")!)
request.HTTPMethod = "DELETE"
var err: NSError?
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(self.API_key, forHTTPHeaderField: "API-Key")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if (error != nil) {
return completionHandler(nil, error)
}
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
println(json)
if (error != nil) {
return completionHandler(nil, error)
} else {
return completionHandler(json, nil)
}
})
task.resume()
}
回到 ViewController 中的 tableView commitEditingStyle 的方法中
將其更新為:
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
api.deleteTodoList({data, err -> Void in
let alert = UIAlertView()
alert.title = "Alert"
alert.addButtonWithTitle("Ok")
if (err != nil) {
alert.message = "Failed to delete: \(err)"
alert.show()
} else {
alert.message = "ok!"
self.fakeData.removeAtIndex(indexPath.row)
dispatch_async(dispatch_get_main_queue(), {
// must be "tableView!" not "tableView?"
alert.show()
self.tableView!.reloadData()
})
}
}, todoId: fakeData[indexPath.row]["_id"]!)
}
改好程式碼後,執行該程式
在清單中將 item 往左滑,就可以看到刪除的按鈕了!
超簡單的啦!