I am trying to delete an object from the class UserRequests via swift only if the object belongs to the current user, and that requestResponded is not equal to true. However, I get an error at objects.deleteInBackground() and the function still doesn't work when I remove this line.
func deleteRequest(){
let check = PFQuery(className: "UserRequests")
check.whereKey("requestResponded", equalTo: "True")
let query = PFQuery(className: "UserRequests")
query.whereKey("username", equalTo: (PFUser.currentUser()?.objectForKey("username") as! String))
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if objects != nil && error == nil{
// Successfully retrieved the object
check.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if error != nil || object == nil {
print("Not accepted.")
object!.deleteInBackground()
objects.deleteInBackground()
} else {
print("Successfully retrieved the object.")
}
}
}else{
self.performSegueWithIdentifier("requestAccepted", sender: self)
}
})
}
It is because objects is an list of object. You should only delete object 1 by 1.
For example:
for object in objects {
object.deleteInBackground()
}
Also, because two queries belong to same class. I would suggest using 1 query
UPDATE
func deleteRequest(){
let query = PFQuery(className: "UserRequests")
// the key "requestResponded" is not True
query.whereKey("requestResponded", equalTo: "False")
// for deleting the object is that it belongs to the current user
query.whereKey("username", equalTo (PFUser.currentUser()?.objectForKey("username") as! String))
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error != nil{
print(error)
}
// objects are those the key "requestResponded" is not True and belongs to the current user
for object in objects {
object.deleteInBackground()
}
// other case
if objects.count == 0 { // no match result found
}
})
}
I guess you still miss the condition of when to perform segue
Related
each cell displays the according comments and photo of the user logged-on. They are loaded with parse.
Now you want to Löschen the button deletes the photo and the comments.
Unfortunately this does not work. Wen I click on the button nothing happens
Unfortunately I understand little of swift and can't get on the solution
The query works, and the app displays the photos and Commons.The query and post code:
override func viewDidLoad() {
super.viewDidLoad()
super.viewDidLoad()
let query = PFQuery(className: "Post")
query.whereKey("username", equalTo: PFUser.current()?.username)
query.findObjectsInBackground(block: { (object, error) in
if let posts = object {
for post in posts{
print(posts)
self.comments.append(post["message"] as! String)
self.imageFile.append(post["imageFile"] as! PFFile)
self.tableView.reloadData()
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
})
}
And here of the "delete"function code that I have tried:
#IBAction func remove(_ sender: Any) {
print("Entered remove")
let query = PFQuery(className: "Post")
query.whereKey("username", equalTo: PFUser.current()?.username)
query.findObjectsInBackground(block: { (object, error) in
if let posts = object {
print(posts)
for post in posts{
print(posts)
if let message = post["message"] as? String, let image = post["imageFile"] as? PFFile {
print("message and image read", message, image)
if let messageIndex = self.comments.index(of: message), let imageIndex = self.imageFile.index(of:image) {
self.comments.remove(at: messageIndex)
self.imageFile.remove(at: imageIndex)
}
}
self.tableView.reloadData()
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
})
}
The output:
I don't get an error message and nothing is deleted.
Thank you for your help
You do not have access to your current index where and object ids.
So based on that you can remove easy.
The more easy way to implement the delete function is to have an array of objectId for your messages:
self.ids.append(post.objectId)
And when you want to delete it:
let query = PFQuery(className: "Post")
query.whereKey("objectId", equalTo: self.ids.index(of: indexPath.row))
// Make a query in background to only get the object that you want to delete
query.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if error != nil || object == nil {
print("The getFirstObject request failed.")
} else if let object = object {
print("Successfully retrieved the object.")
object.deleteInBackground()
}
}
Having different arrays representing the same object is not really good to do. So a better way to handle you problem is have only one array for your post
When you fetch it you can do something like that:
guard let user = PFUser.current() else { return }
let query = PFQuery(className: "Post")
query.whereKey("username", equalTo: user.username)
query.findObjectsInBackground(block: { (posts, error) in
if let posts = posts {
self.posts = posts
}
})
With this way when you want to delete it in the remove function:
if indexPath.row < self.posts.count {
self.posts[indexPath.row].deleteInBackground()
}
I would like to delete an object from Parse when I un-check the table row.
The issue occurs when trying to delete objects from Parse after having queried them.
this is my code:
if cell.accessoryType == UITableViewCellAccessoryType.Checkmark {
cell.accessoryType = UITableViewCellAccessoryType.None
var query = PFQuery(className:"Followers")
query.whereKey("follower", equalTo: "\(PFUser.currentUser()?.username)")
query.whereKey("following", equalTo: "\(cell.textLabel?.text)")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
for object in objects as! [PFUser] {
object.deleteInBackground()
}
} else {
println(error)
}
}
}
I think the issue is in your query.findObjectsInBackgroundWithBlock
i think its because you are defining objects as! [PFUser] instead of a [PFObject]
try this it should do the trick
query.findObjectsInBackground { (objects, error) in
if error == nil,
let objects = objects {
for object in objects {
object.deleteInBackground()
}
}
I want to delete objects from parse
Yes in the Parse iOS SDK to delete multiple objects in background at once on Parse server, you can use deleteAllInBackground
You can use it with 2 different ways:
PFObject.deleteAll(inBackground: [PFObject]?)
PFObject.deleteAll(inBackground: [PFObject]?, block: PFBooleanResultBlock?)
For example:
query.findObjectsInBackgroundWithBlock({ (objects : [PFObject]?, error: NSError?) -> Void in
PFObject.deleteAll(inBackground: objects)
})
You can also see this post
I hope my answer was helpful 😊
How can I use a query to find the currentUser from a Parse Class and then write data into that user columns?
var query = PFQuery(className:"User")
query.whereKey("objectId", equalTo:PFUser.currentUser()!)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
println(object.objectId)
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
Change this line
query.whereKey("objectId", equalTo:PFUser.currentUser()!)
To:
query.whereKey("objectId", equalTo:PFUser.currentUser().objectId)
And also if you are querying from the parse user class it should be _User not User
To Only save data
var ObjectToSave = PFObject(className: "_User")
ObjectToSave["raw"] = "whateveryoulike"
ObjectToSave["UserId"] = PFUser.currentUser()?.objectId // this piece of code is when you create a new class
ObjectToSave.saveInBackgroundWithBlock { (success:Bool, error:NSError?) -> Void in
if error == nil{
println("data was saved")
}
else
{
println("error")
}
}
}
I don't think it is a good idea to save other data into the _User class, you should leave this class for the login or sign up. You should create a new class then save all new data with the userid...
you don't need to query for the current user.
Use this
var user = PFUser.currentUser()
user["one"] = "whateveryoulike"
user["two"] = "whateveryoulike"
user.saveInBackgroundWithBlock { (success:Bool, error:NSError?) -> Void in
if error == nil{
println("data was saved")
}
else
{
println("error")
}
}
}
I tried this:
var data:NSMutableArray = NSMutableArray()
func loadData() {
var userQuery = PFUser.query()!
userQuery.whereKey("objectId", equalTo: PFUser.currentUser()!.objectId!)
userQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.data.addObject(object)
}
}
}
println(data) // this gives an empty NSMutableArray.
}
Is there any other way to get the data of current user? , I am doing this to make the profile Screen of the current user..Thanks for your time..
Use this to access the current user
if PFUser.currentUser() != nil {
PFUser.currentUser()!.fetchIfNeededInBackgroundWithBlock({ (user: PFObject?, error: NSError?) -> Void in
if user != nil {
var u = user as! PFUser
//Access the fetched user HERE
}
})
//NOT here, it will be nil here
}
I am working with Parse for the first time in my application, and everything seems to be working well with the exception of when I go to change existing data. I am simply trying to change a string value that I have stored in a column of one of my items.
This is the code I currently have:
func sendTimeToParse() {
var query = PFQuery(className: "ClassName")
query.whereKey("Name", equalTo: rideNamePassed)
query.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if error != nil {
println("The getFirstObject request failed.")
} else {
// The find succeeded.
let object = PFObject(className: "ClassName")
object.setValue(self.timeSelected, forKey: "WaitTime")
object.saveInBackground()
println("Successfully retrieved the object.")
}
}
}
}
At the moment it just seems to create a new row of data and saves the time to that, however obviously I would like it to change the existing data in whatever row matches the name of the current record.
Anyone have any suggestions?
The problem is that you are creating a new PFObject with the line let object = PFObject(className: "ClassName") instead of using the retrieved object which is given as a parameter.
Simply delete the line let object = PFObject(className: "ClassName") and unwrap the received optional. It could look something like the following:
func sendTimeToParse() {
var query = PFQuery(className: "ClassName")
query.whereKey("Name", equalTo: rideNamePassed)
query.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if error != nil {
println("The getFirstObject request failed.")
} else {
if let obj = object {
obj.setValue(self.timeSelected, forKey: "WaitTime")
obj.saveInBackground()
}
println("Successfully retrieved the object.")
}
}
}