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.
Related
I'm trying to query a class of objects with specific ID's to delete. When I run it however, I get an error for "This query has an outstanding network connection. You have to wait until it's done". I assume this is because I'm trying to delete an object while I'm still accessing it.
I've provided the deletion code in the closure because I'm assuming the closure statements only execute after the function call finishes, yet it's still giving me the error. I've also tried using DispatchGroups because it does seem like a concurrency issue, but I'm not too familiar with their usage yet. Here's my code:
let idList = [...] // Some list of ID's I would like to remove
let query = PFQuery(className: "Pictures")
for id in idList {
query.getObjectInBackground(withId: id) { (object: PFObject?, error:
Error?) in
if error == nil {
img?.deleteInBackground() { (success, error: Error?) ...
}
}
I'm expecting each object associated with an ID in my original IdList to be deleted from the Parse backend. However, it seems that getObjectInbackground() and deleteInBackground() are clashing. If anyone could provide some advice, that would be wonderful!
You can try
var idList = [...]
func delete(_ id:Int) {
query.getObjectInBackground(withId: id) { (object: PFObject?, error: Error?) in
if error == nil {
img?.deleteInBackground() { (success, error: Error?) ...
}
idList = Array(idList.dropFirst())
if !idList.isEmpty {
delete(idList.first!)
}
}
}
Initially call it like
delete(idList.first!)
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!
Could anyone tell me why my startingPoints array is still at 0 elements? I know that I am getting objects returned during the query, because that print statement prints out each query result, however it seems like those objects are not getting appended to my local array. I've included the code snippet below...
func buildStartSpots() -> Void {
let queryStartingPoints = PFQuery(className: "CarpoolSpots")
queryStartingPoints.whereKey("spotCityIndex", equalTo: self.startingCity)
queryStartingPoints.findObjectsInBackgroundWithBlock{(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
for object in objects! {
print("starting point: \(object)")
self.startingPoints.append(object)
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
print("starting points")
dump(self.startingPoints)
}
While I have no experience in Parse, the block is asynchronously executed and likely non-blocking as dictated by the method name of the API call. Therefore, it is not guaranteed that the data would be available at the time you call dump, since the background thread might still be doing its work.
The only place that the data is guaranteed to be available at is the completion block you supplied to the API call. So you might need some ways to notify changes to others, e.g. post an NSNotification or use event stream constructs from third party libraries (e.g. ReactiveCocoa, RxSwift).
When you try to access the array, you need to use it within the closure:
func buildStartSpots() -> Void {
let queryStartingPoints = PFQuery(className: "CarpoolSpots")
queryStartingPoints.whereKey("spotCityIndex", equalTo: self.startingCity)
queryStartingPoints.findObjectsInBackgroundWithBlock{(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
for object in objects! {
print("starting point: \(object)")
**self.startingPoints.append(object)**
}
//use it here
startingPoints xxx
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
print("starting points")
dump(self.startingPoints)
}
I am able to get the application functioning as intended and will close this answer out.
It seems as though that the startingPoints array is not empty, and the values I need can be accessed from a different function within that same class.
The code snippet I am using to access my locally stored query results array is here:
for object in self.startingPoints {
let startingLat = object["spotLatitude"] as! Double
let startingLong = object["spotLongitude"] as! Double
let carpoolSpotAnnotation = CarpoolSpot(name: object.valueForKey("spotTitle") as! String, subTitle: object.valueForKey("spotSubtitle") as! String, coordinate: CLLocationCoordinate2D(latitude: startingLat, longitude: startingLong))
self.mapView.addAnnotation(carpoolSpotAnnotation)
The code snippet above is located within my didUpdateLocations implementation of the locationManager function, and with this code, I am able to access the query results I need.
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'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.