Search code examples
iosparse-platformpfuserpfquerytableviewcontrolle

PFQueryTableView queryForTable(), how to return nothing?


I just started using Parse and have a few problems sometimes. I have a PFQueryTableView which works perfect when a user is logged in. The queryForTable() function queries all the objects that have the current users username in their "createdBy" column. But if no User is logged in, what do I return then? At the moment I have it like this, which works, but gives an error in the Log. After the user logged in, you have to pull to refresh the Table, then it shows the users events. I would like to have an empty table when no User is logged in, and after a User logged in and the loginView disappeared, the table should automatically load the users data. Here are my viewDidAppear and my queryForTable functions:

override func viewDidAppear(animated: Bool) {

    if PFUser.currentUser() == nil {
        let loginView = PFLogInViewController()
        loginView.delegate = self
        self.presentViewController(loginView, animated: true, completion: nil)



    }

}


override func queryForTable() -> PFQuery {

    if PFUser.currentUser() != nil{

            let query = PFQuery(className: "calendarEvents")
            query.cachePolicy = .CacheElseNetwork
            query.orderByAscending("StartDate")
            query.whereKey("createdBy", equalTo: (PFUser.currentUser()?.username)!)
            return query
   }else{
        let noQuery = PFQuery()

        return noQuery
    }


}

Solution

  • The approach you've chosen is fine. A more common approach is to not even present this VC until the app has a user. You could also add all users to some role, and then protect your "calendarEvents" class with a CLP that refers to that role.

    Another idea on the query is to add a qualifier that guarantees an empty result, for example...

    override func queryForTable() -> PFQuery {
        let query = PFQuery(className: "calendarEvents")
        query.cachePolicy = .CacheElseNetwork
        query.orderByAscending("StartDate")
        query.whereKey("createdBy", equalTo: (PFUser.currentUser()?.username)!)
    
        if PFUser.currentUser() == nil {
            query.whereKey("createdAt", greaterThan: NSDate.distantFuture())  // return objects created after the universe has collapsed
        }
        return query
    }