Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Ribbit Swift/Parse : search for a PFUser using UISearchBar

Hello, i trie to find parse users via UISearchBar and display results in a table view. When i heat search, nothing happened... My idea was to use the searchText.text as a query to PFUser.

Should i try to use searchBar with search display controller instead ? Any idea ?

     import UIKit

      class AllFriendsTableViewController: UITableViewController, UISearchBarDelegate,      UISearchDisplayDelegate {
      @IBOutlet var SearchDisplay: UISearchDisplayController!

      var userList:NSMutableArray = NSMutableArray()

      func searchBarShouldBeginEditing(searchBar: UISearchBar!) -> Bool {
      return true
      }

       func searchBarShouldEndEditing(searchBar: UISearchBar!) -> Bool {
      return true

       }

       func searchBar(searchBar: UISearchBar!, textDidChange searchText: String!) {
      loadUser()
     }

      @IBOutlet var searchText: UISearchBar!

     func loadUser () {

      userList.removeAllObjects()
       var findUser:PFQuery = PFUser.query()
       findUser.whereKey("username", equalTo: searchText.text)


        findUser.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error:NSError!) -> Void in
         if !(error != nil) {
        // The find succeeded.
        println("succesfull load Users")
        // Do something with the found objects
        for object  in objects  {
            self.userList.addObject(object)
            println("users added to userlist")
        }
        self.tableView.reloadData()
         } else {
        // Log details of the failure
        println("error loadind user ")
        println("error")
         }

        }
         }


         override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
       return 1
         }

       override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
       if tableView == searchDisplayController.searchResultsTableView {
         return userList.count
      }
      else {
         return 0
        }
         }

        override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

         let cell: AllFirendsTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)as                 AllFirendsTableViewCell


    let users:PFObject = self.userList.objectAtIndex(indexPath!.row) as PFObject


        var findUserName:PFQuery = PFUser.query()
       findUserName.whereKey("username", containsString: searchText.text)

       findUserName.findObjectsInBackgroundWithBlock{
        (objects:[AnyObject]!, error:NSError!) -> Void in

         if !(error != nil) {

             if let user:PFUser = users as? PFUser {
            cell.userNameTextField.text = user.username
            println("user exist")
            // define avatar poster

            if let avatarImage:PFFile = user["profileImage"] as? PFFile {
                avatarImage.getDataInBackgroundWithBlock{(imageData:NSData!, error:NSError!)-> Void in

                    if !(error != nil) {

                        let image:UIImage = UIImage(data: imageData)


                        cell.avatarImage.image = image as UIImage
                        cell.avatarImage.layer.cornerRadius = 24
                        cell.avatarImage.clipsToBounds = true

                    }

                }

            }
            else {
                cell.avatarImage.image = UIImage(named: "Avatar-1")
                cell.avatarImage.layer.cornerRadius = 24
                cell.avatarImage.clipsToBounds = true
            }
        }

       }
       }

          return cell

         }
        override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)
         navigationController.navigationBar.hidden = false
        loadUser()

         }

        override func viewDidAppear(animated: Bool) {

        }

        override func viewDidLoad() {


          // Do any additional setup after loading the view, typically from a nib.
      }
       }

2 Answers

you dont need a search display controller, you can just drag a search bar into the top of your tableView controller. you need to connect the search bar to your view controller as a property and then you need to set your search bars delegate in view did load:

 override func viewDidLoad() {


          //set search bars delegate
          self.searchBar.delegate = self

      }

What do you mean "as a property"? Is it not already linked as a property via

 @IBOutlet var searchText: UISearchBar!

If this is the case, I should just be able to add this:

 override func viewDidLoad() {


          //set search bars delegate
          self.searchText.delegate = self

      }

But that doesn't work for me.

Found the problem. I needed to delete this:

override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
       if tableView == searchDisplayController.searchResultsTableView {
         return userList.count
      }
      else {
         return 0
        }
         }

and replace it with this:

override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
         return userList.count
        }

Perfect it work good ! Thanks a lot !