swiftparse-platformpfrelation

Perform action when all responses are retrieved from Parse


I have two models, subclassing from PFObject:

** a Recipe model

class Recipe: PFObject, PFSubclassing{
  class func parseClassName() -> String {
    return "Recipe"
  }

 @NSManaged var name: String?
 var toIngredients: PFRelation! {
   return relationForKey("ingredients")
 }
}

** an Ingredient model:

class Ingredient: PFObject, PFSubclassing{
  class func parseClassName() -> String {
      return "Ingredient"
  }
  @NSManaged var category: String?
  @NSManaged var ingredient: String?
  @NSManaged var amount: NSNumber?
  @NSManaged var unit: String?
}

I found out that getting the ingredients for a single recipe, would work like this:

 let query = recipe.toIngredients.query()
 query.findObjectsInBackgroundWithBlock{....

My problem is that I have an array of recipes, that I need to get ingredients from. I need to combine the multiple asynchronous responses to use in another controller. I need to grab the whole list of ingredients, and then perfromSegueWithIdentifier.

I found this stackoverflow post: Checking for multiple asynchronous responses from Alamofire and Swift

Is this the right approach for using Parse and PFRelation?


Solution

  • Basically you need execution in parallel of multiple tasks, and be notified when all of them completed. You can achieve this if you use findObjectsInBackground() which returns a BFTask. Once you have the array of tasks, you can send them for execution in parallel (more details here):

    let tasks = recipes.map { $0.toIngredients.query().findObjectsInBackground() }
    let aggregateTask = BFTask(forCompletionOfAllTasks: tasks)
    aggregateTask.continueWithBlock { task in
        if task.error() { 
            // handle the error
        } else {
           // grab the results, perform the seque
        }
    }