使用Swift中的Parse删除表视图单元格

时间:2017-12-23 01:52:43

标签: swift database heroku parse-platform

我有我的应用程序,我有用户会发布问题。我希望用户能够删除他们的帖子,这是我能够做到的。这是我的代码。

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){
    if editingStyle == UITableViewCellEditingStyle.delete{
        print("here1")
        let query = PFQuery(className: "Post")
        query.whereKey("user", equalTo: PFUser.current())
        print("here2")
        query.findObjectsInBackground(block: { (objects, error) in
            if error != nil {
                print("THERE WAS AN ERROR DELETING THE OBJECT")
            }else{
                for object in objects!{
                    print("here3")
                    object.deleteInBackground()
                    tableView.reloadData()
                }
            }
        })
    }
}

正如预期的那样,我的代码删除了当前用户的所有帖子。我不知道如何获取所选帖子并仅删除该帖子。 以下是数据库的结构

{
"_id": "EZY40tN2FR",
"location": [
    -122.0312186,
    37.33233141
],
"question": "Sldfksdlkfjsldfkjsldkfjsldkjf",
"category": "Entertainment",
"_p_user": "_User$R9GdCYnVno",
"_created_at": {
    "$date": "2017-10-17T01:03:11.438Z"
},
"_updated_at": {
    "$date": "2017-10-17T01:03:11.438Z"
}
}

感谢您的帮助!

获取数据的代码:

override func queryForTable() -> PFQuery<PFObject> {
        let query = PFQuery(className: "Post")
        query.includeKey("user")
        query.whereKey("user", equalTo: PFUser.current()!)
        query.order(byDescending: "createdAt")
        query.limit = 100
        return query
    }

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式删除对象:

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){
    if editingStyle == UITableViewCellEditingStyle.delete{
        print("here1")
        let objectToDelete = objects?[indexPath.row] as! PFObject
        objectToDelete.deleteInBackgroundWithBlock { (success, error) in
            if (success) {
                // Force a reload of the table - fetching fresh data from Parse platform
                self.loadObjects()
            } else {
                // There was a problem, check error.description
            }
        }

    }
}