Basically, I am working on a chat app. In order to retrieve "room" objects from parse, I am using a query like this:
func loadData(){
rooms = [PFObject]()
users = [PFUser]()
self.tableView.reloadData()
let pred = NSPredicate(format: "user1 = %@ OR user2 = %@", PFUser.currentUser()!, PFUser.currentUser()!)
let roomQuery = PFQuery(className: "Room", predicate: pred)
roomQuery.orderByDescending("lastUpdate")
roomQuery.includeKey("user1")
roomQuery.includeKey("user2")
roomQuery.findObjectsInBackgroundWithBlock { (results, error) -> Void in
if error == nil {
self.rooms = results as! [PFObject]
for room in self.rooms {
let user1 = room.objectForKey("user1") as! PFUser
let user2 = room["user2"] as! PFUser
if user1.objectId != PFUser.currentUser()!.objectId {
self.users.append(user1)
}
if user2.objectId != PFUser.currentUser()!.objectId {
self.users.append(user2)
}
}
self.tableView.reloadData()
}
}
}
Now, this is working fine when it comes to find any rooms that the current user is a member of. What I want to do is that somewhere in the app, I also have an array of usernames(String type).
So the question is: how do I use the above NSPredicate
, in such a way that the results/PFObject
returned are also assured to match any of the usernames in the array for the usernames of user1 or user2.
(Basically, the idea is that, that array represents your contacts and if someone is no longer one you should no longer see that room)
Please pretty please? :<
You should create an array of the allowed users, including the current user and placeholder objects for all your other user ids (see
objectWithoutDataWithClassName:objectId:
). then use that array in your query withIN
instead of testing for direct equality (=
).