I've used Parse successfully in other apps before but never used the delete function. I'm trying to delete a value ( an alphabetical letter) in a column (column title is 'letter') associated with a user in Parse. I'm using Swift. The code is finding the correct value as evident via a println in the deletion code, but nothing is happening after the remove and save functions are executed. The value is still there in the column. And I'm not getting any Parse errors. The code is below. Any help, as always, will be greatly appreciated.
var query = PFQuery(className: "game")
query.whereKey("player", equalTo:PFUser.currentUser())
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if !(error != nil) {
for object in objects {
var myLetter = object["letter"]! as String
println("The object for key letter is \(myLetter)") //This prints the correct letter in the current user's Letter column
PFUser.currentUser().removeObjectForKey("letter")
PFUser.currentUser().saveInBackgroundWithBlock{
(success: Bool, error: NSError!) -> Void in
if (success) {
// The object has been saved.
println("success")
} else {
// There was a problem, check error.description
println(error)
}
}
}
}
}
I think the issue is that you are creating a new Parse query and deleting it locally as opposed to retrieving the item and then deleting it. So, retrieve the item you want to delete and then call the deleteInBackground method.
Related
I have been trying to figure out this problem for a while without success. I have a button works like this:
Query the videosTable class in Parse and if the value for videoID (that I get from youtube's API) is not existent, create a new PFObject with rating 0. Otherwise, increase the rating by one.
The result however, is that the first new object I try to create every time I launch the app has no problem, but if I create another new object during the same run/session, the object previously created gets replaced by this new one.
The objectID stays the same, so I'm guessing this has something to do with the query not getting closed (or something similar), resulting in me modifying the previous object, instead of creating a new one.
Can someone shed some light in this?
#IBAction func recomBtn(sender: AnyObject) {
let query = PFQuery(className: "VideosInfo")
query.whereKey("Video_ID", equalTo: videoID)
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if objects?.count == 0 {
print(objects)
videosTable["Video_ID"] = self.videoID
videosTable["Rating"] = 1
videosTable.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
print("Rating Created")
} else {
print(error?.description)
}}
} else {
objects![0].incrementKey("Rating")
print("Rating Increased")
videosTable.saveInBackground()
}} else {
print(error?.description)
}
}
}
After much reviewing, I found out I was making a very dumb mistake! I declared the PFObject outside of the function! So when I was done with my button, the PFObject remained! (Since I don't really close the view after I go to another video, the PFObject remained as a property of the class until I closed the app).
Thanks anyway for your help!
This is for an existing class on Parse called "HellsKitchen" and I have tried others, but always receive nil on objects.
let query = PFQuery(className: "HellsKitchen")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
print("got em: \(objects)")
} else {
print("error: \(error!.userInfo)")
}
}
All of the other posts about this refer to the block closure when they had objects as [AnyObject]? but it has since changed sometime in late 2015 and I no longer need to cast it as PFObject as all the answers say.
I have tried adding App Transport Security Settings > Allow Arbitrary Loads = YES to my Info.plist to no avail.
I get no error from the block either. It passes into the if statement because error == nil and prints "got em: nil".
How can I get my objects?
I'm trying to query a nonexistent object like this code bellow, but always "Mike" is found. What could be wrong? Everything is working great (Save, Delete, Update and Query without error recognition).
var query = PFQuery(className:"Restaurant")
query.whereKey("clientname", equalTo:"Mike")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if (error == nil) {
print ("Found")
}
else {
print ("Not Found")
}
}
Try checking (debugging) what "objects" actually is. I think you will see that it is an empty array, meaning it did NOT find Mike.
An empty array of results is not a query error. The query succeeds, but finds no objects. So not getting an error does not mean "Found". It just means there was no error.
I' trying to save song info to parse, but if the song already exist in parse I want my code just do nothing.
I've tried this code below:
var Music = PFObject(className:"Musics")
var query = PFQuery(className:"Musics")
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 {
var songTitle = object.objectForKey("songTitle") as? String
if songTitle != title {
Music["createdBy"] = PFUser.currentUser()
Music["songTitle"] = title
Music["albumCover"] = imageFile
Music["songArtist"] = artist
Music.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
println("succeed")
} else {
// There was a problem, check error.description
println("error jeh")
}
}
}else{
println("song already exist")
}
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
the code above give below result on log:
Successfully retrieved 4 scores.
song already exist
Successfully retrieved 4 scores.
song already exist
Successfully retrieved 4 scores.
song already exist
Successfully retrieved 4 scores.
song already exist
succeed
succeed
succeed
succeed
succeed
succeed
succeed
succeed
succeed
succeed
succeed
succeed
Why my for loop , looping more than the Objects.count? and how can I prevent dupiclate entry on parse?
give me any advice, doesn't matter in obj c or swift
I suggest to implement a simple beforeSave trigger, on Parse Cloud code, in order to check if the new entry song already exist (basically you're going to make one or more field uniques. For example:
Parse.Cloud.beforeSave("Musics", function(request, response) {
var newEntrySong = request.object;
var querySongs = new Parse.Query("Musics");
querySongs.equalTo("title", newEntrySong.get("title"));
querySongs.equalTo("description", newEntrySong.get("description"));
// this could be a sort of signature for your song, to make more unique (skipping spaces and new lines for example)
querySongs.equalTo("md5Title", newEntrySong.get("md5Title"));
querySongs.first({
success: function(temp) {
response.error({errorCode:123,errorMsg:"Song already exist!"});
},
error: function(error) {
response.success();
}
});
});
Hope it helps.
I want to unpin a list of objects, which I had successfully locally stored earlier, and replace it with a new one. The code below should do that trick, but the locally pinned objects simply don't get updated. I tried everything including PFObject.unpin, nothing removes the old pinned objects except a complete reset of the simulator
func updateCountryList(server:Int, local:Int) {
let query = VEPCountry.queryAll()
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error != nil {
// throw error
} else {
if local != 0 {
VEPState.unpinAllObjectsWithName(String("countryListVersion\(local)"))
}
VEPState.pinAll(objects, withName: String("countryListVersion\(server)"))
defaults.setObject(server, forKey: "localCountryListVersion")
}
}
}
Appreciate help or pointer to known issues around unpinning in Swift
I wonder if your unpin has't really finished, it's going off to the database after all.
Can you try:
query
.findObjectsInBackground()
.continueWithSuccessBlock({ (task: BFTask!) -> AnyObject! in
// ...
return VEPState.unpinAllObjectsWithNameInBackground("name"))
})
.continueWithSuccessBlock({ (task: BFTask!) -> AnyObject! in
// ...
return VEPState.pinAllInBackground(objects, withName: "name"))
})
I may have the syntax a little off and the background method names not quite right. Also I'm using promises/tasks which is not a bad habit to get into.