Aidan Kaiser
Aidan Kaiser

Reputation: 521

Check if query key is nil Parse

So, I have a query in parse that has to find objects based on whether a key is equal to a certain object. Here is the few lines of code.

    var gamesQuery = PFQuery(className: "Games")
    gamesQuery.whereKey("challenged", equalTo: (PFUser.currentUser()!.objectId!))
    gamesQuery.whereKey("challenger", equalTo: PFUser.currentUser()!)

However, when this query is ran, the query is occasionally found as nil due to the fact that there is no object that fits the search parameters.

Is there any check that I could run that could check if

gamesQuery.whereKey("challenged", equalTo: (PFUser.currentUser()!.objectId!))

is nil? Any help with this issue would be very appreciated.

Upvotes: 1

Views: 236

Answers (1)

Paulw11
Paulw11

Reputation: 114865

Your current query is essentially an and - "find objects where challenged==current user and challenger==current user".

I think you are after an or query - "find objects where challenged==current user or challenger==current user". You can do this with a compound query in Parse -

let challengedQuery = PFQuery(className: "Games")
challengedQuery.whereKey("challenged", equalTo: (PFUser.currentUser()!.objectId!))

let challengerQuery = PFQuery(className: "Games")
challengerQuery.whereKey("challenger", equalTo: PFUser.currentUser()!)

let gamesQuery = PFQuery.orQueryWithSubqueries([challengedQuery, challengerQuery])

gamesQuery.findObjectsInBackgroundWithBlock {
  (results: [PFObject]?, error: NSError?) -> Void in
  if error == nil {
     // results contains challenger and challenged games.
  }
}

Upvotes: 2

Related Questions