UISearchController does not delete the result when I delete them

1.4k Views Asked by At

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.

2

There are 2 best solutions below

5
On BEST ANSWER

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()
3
On

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
}