Running Parse code after another has finished execution - ios

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!)

Related

Parse query results aren't being added (appended) to a local array in iOS Swift

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.

Why does the "objects: [PFObject]?" parameter of Parse's findObjectsInBackgroundWithBlock function return nil?

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?

Parse with Swift: handle network error manually

I have been trying to modify the following code to manually handle network errors (e.g. disconnection) when retrieving users (_User table) from Parse. As soon as the error returned from the PFQuery is not nil, I should return the completionHandler with the errorMsg, however, the following code doesn't seem to return. Instead the Parse SDK error message keeps printing:
var status: Bool = false
var errorMsg: String? = nil
var query = PFQuery(className: ParseClient.ClassNames.User) //default limit - 100
query.whereKey("email", containsString: "#").findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
status = true
didComplete(success: status, students: objects as! [PFUser], error: nil)
return
} else {
dispatch_async(dispatch_get_main_queue()) {
println("error in fetching all users from Parse")
errorMsg = "There are network problems in fetching user data, please try again later."
didComplete(success: status, students: nil, error: errorMsg)
return
}
}
}
Parse network error message:
2015-09-01 21:28:59.881 UserGame[3564:354410] [Error]: Network connection failed. Making attempt 3 after sleeping for 5.993194 seconds.
Your second return is inside your dispatch_async block, and I think you meant to put it outside.
That said, I'm pretty sure you can't stop Parse from retrying, at least not from within this block. You could also try:
query.cancel()
This "cancels the current network request (if any)."

Parse Local Datastore: Unpin objects seems broken in Swift

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.

Parse: deleting object value in column using Swift

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.

Resources