简体   繁体   中英

Deleting Table View Cell with Parse in Swift

I have my app, which I have users which will post questions. I want the users to be able to delete their posts, which I sort of have been able to do. Here is my code.

    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()
                }
            }
        })
    }
}

As expected my code deleted all the posts from the current user. I don't know how to get just the selected post and delete only that one. Here is how the data base is structured

{
"_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"
}
}

Thanks for your help!

Code for Getting Data:

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
    }

You can get your object to delete in this way:

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
            }
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM