1

I implemented UISearchController in my app to search for users to follow and unfollow. I am using swift and Parse as a backend. The problem is, whenever I want to type something and then delete it, it keeps the retrieved results and does not delete them. When there is no result, the table view shows "No result" with the retrieved results because there are not deleted!! I can't figure out what is the problem. Any help?

Here is the code,

UISearchController delegate and methods,

// To search
 var userSearchController: UISearchController!
 var resultsController = UITableViewController()
 var searchActive: Bool = false

// To follow and unfollow users
var userIds = [""]
var isFollowing = ["":false]


// MARK: - Lifecycle

override func viewDidLoad() {
    super.viewDidLoad()

    // tableview delegate and datasource
    self.resultsController.tableView.dataSource = self
    self.resultsController.tableView.delegate = self

    self.resultsController.loadViewIfNeeded()
    configureSearchController()
}

func configureSearchController(){

    self.userSearchController = UISearchController(searchResultsController: nil)
    // Set the search controller to the header of the table
    self.tableView.tableHeaderView = self.userSearchController.searchBar
    // This is used for dynamic search results updating while the user types
    // Requires UISearchResultsUpdating delegate
    self.userSearchController.searchResultsUpdater = self
    self.userSearchController.dimsBackgroundDuringPresentation = false
    self.definesPresentationContext = true

    // Configure the search controller's search bar
    self.userSearchController.searchBar.placeholder = "Search for a parent"
    self.userSearchController.searchBar.sizeToFit()
    self.userSearchController.searchBar.delegate = self
}

// MARK: - Search Bar Delegate Methods

func searchBarSearchButtonClicked(searchBar: UISearchBar) {

    let searchString: String = searchBar.text!.lowercaseString
    if searchActive == false {
        searchActive = true
        // Force search if user pushes button
        if (searchString != "") {
            loadSearchUsers(searchString)
        }

        self.resultsController.tableView.reloadData()

    }
}

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchActive = true

}

func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    searchActive = false

}


func searchBar(searchBar: UISearchBar, textDidChange searchText: String){

    if (searchBar.text == ""){
        searchActive = false
    }
    else {
        searchActive = true
        let searchString: String = searchBar.text!.lowercaseString
        if (searchString != ""){
            loadSearchUsers(searchString)}
    }

}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {

    searchActive = false
    searchBar.text = ""
    self.searchUsers.removeAll(keepCapacity: false)

    self.resultsController.tableView.reloadData()

}

func updateSearchResultsForSearchController(searchController: UISearchController) {

    if let searchString: String = searchController.searchBar.text!.lowercaseString {

        if (searchString != "" && !self.searchActive) {
            loadSearchUsers(searchString)
        }
    }
}

Here is the numberOfSectionsInTableView

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    var numOfSection: NSInteger = 0

     if userIds.count > 0 {
        //self.resultsController.tableView.reloadData()
        self.tableView.backgroundView = nil
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
        numOfSection = 1


    } else {

        let noDataLabel: UILabel = UILabel(frame: CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height))
        noDataLabel.text = "No result."
        noDataLabel.textColor = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 180.0/255.0, alpha: 1.0)
        noDataLabel.textAlignment = NSTextAlignment.Center
        self.tableView.backgroundView = noDataLabel
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }

    return numOfSection
}

Let me know if you need more information. Thank you so much.

Amal Nasir
  • 164
  • 15
  • @Russell hi Russell! I got your UISearchController from here, http://stackoverflow.com/questions/32356676/smart-search-for-parse-usernames-in-swift-not-working and worked for me, but I have this problem, would you help me ? – Amal Nasir Feb 26 '16 at 17:48

2 Answers2

0

Table data wont get deleted just because you made changes in search text. You have to clear the data-set first and then set the search result into data-set and then reload, You already do this in searchBarCancelButtonClicked method.

self.searchUsers.removeAll()
self.searchUsers.appendContentsOf(results)
self.resultsController.tableView.reloadData()
Tejas Ardeshna
  • 4,343
  • 2
  • 20
  • 39
RJE
  • 781
  • 6
  • 14
  • What do you mean by result here? self.searchUsers.appendContentsOf(results) – Amal Nasir Feb 26 '16 at 17:44
  • Do you mind if I send you a demo?? This problem frustrate me!! – Amal Nasir Feb 26 '16 at 20:36
  • @TejasArdeshna Do you think I am only able to use UISearchController to search the data already within my app ? Do I need all the data be there in my my app to filtered through them? – Amal Nasir Feb 28 '16 at 15:00
  • 'results' can be from any source, if you have some thing to filter thought you do it first and identify a list of items you need to display and after that you can remove the data-set items and add these filtered results. Then just simple reloadData will display them. – RJE Feb 29 '16 at 04:53
  • Would you mind if I send you my code to check? I solved one issues and another just came out!! I really don't know what is the problem. Whenever I type a space,"" , it returns all the data that are stored in Parse. In addition, when I try to delete what I just typed, every thing goes except the buttons, I have name, image and button on my cell. Im sorry if I am bothering you. would you please help me? – Amal Nasir Feb 29 '16 at 06:19
0

Maybe you forgot table.reloadData(). Try this code

@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var table: UITableView!

var dataArray = [1 : "first" ,2 : "second",3 :"third",]
var filteredArray = [String]()
var gotResult = false

override func touchesBegan(touches: Set<UITouch>, withEvent event:   UIEvent?)
{
    self.view.endEditing(true);
    self.searchBar.endEditing(true)
    gotResult = false
    table.reloadData()
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar)
{
    gotResult = true
    table.reloadData()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
    if !gotResult
    {
        gotResult = true
        table.reloadData()
    }
    searchBar.resignFirstResponder()
}

func searchBar(searchBar: UISearchBar, textDidChange searchedText: String)
{

    filteredArray = dataArray.values.filter({ (Items) -> Bool in
        let currentItem: NSString = Items

        return (currentItem.rangeOfString(searchedText, options: NSStringCompareOptions.CaseInsensitiveSearch).location) != NSNotFound
    })

    self.table.reloadData()
}
//Codes for table 
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if gotResult {
        return filteredArray.count
    }
    else {
        return dataArray.count
    }
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = UITableViewCell();
    let value = Array(dataArray.values)[indexPath.row]

    if gotResult {
        cell.textLabel?.text = filteredArray[indexPath.row]
    }
    else {
        cell.textLabel?.text = value

    }

    return cell
}
Marco Castano
  • 150
  • 3
  • 12
  • Thank you for your reply!! But I have question. Do you think I am only able to use UISearchController to search within my app ? – Amal Nasir Feb 28 '16 at 14:39
  • What I meant, the data is not in my tableviewcontroller. I want to search directly from Parse. Can I use UISearchController to do that? Or should I have the data in my tableviewcontroller? – Amal Nasir Feb 28 '16 at 23:11
  • Ah sorry, no I don't think data have to be in your tableviewcontroller – Marco Castano Feb 29 '16 at 09:11