Search code examples
swiftuitableviewuisearchbar

Search bar in table view fails


I have a problem with my search bar. Im trying to search in a table view with search bar, but when I am typing something it shows nothing, and after I deleted all I tried to search all the restaurants disappear.

This is the code I am using. Ill post only what necessary

extension HomeViewController: UISearchBarDelegate{
    //MARK: Search bar
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
      
        filteredData = []
        if searchText == "" {
        
            filteredData = datas
        }
        else {
       
            for restaurante in datas{
           
                if restaurante.title.lowercased().contains(searchText.lowercased())
            {
           
                    filteredData.append(restaurante)
            }
            
        }
        }
        self.homeTableView.reloadData()
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { // Dispare tastatura cand apasam pe search
        searchBar.resignFirstResponder()
    }
    
}





This is the variables :

struct Category {
    let title: String
    let photoKeyHome: String
}


  let datas: [Category] = []
  var filteredData: [Category]!
   
override func viewDidLoad() {
        super.viewDidLoad()
        
        filteredData = datas
}





This is my table view. Maybe im doing something wrong here.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filteredData.count
        
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = homeTableView.dequeueReusableCell(withIdentifier: "homeTableViewCell", for: indexPath) as! homeTableViewCell
        let restaurant = filteredData[indexPath.row]
       
        let storageRef = Storage.storage().reference()
        let photoRef = storageRef.child(restaurant.photoKeyHome)
        
        
        
        cell.myLabel.text = restaurant.title
        cell.myImage.sd_setImage(with: photoRef)

For the datas, im using Firestore and firebase storage. This is how im getting data from the Firestore.

  func getDatabaseRecords() {
            
            let db = Firestore.firestore()
           //  Empty the array
          filteredData = []
            
            db.collection("HomeTableViewRestuarants").getDocuments { (snapshot, error) in
                if let error = error {
                    print(error)
                    return
                } else {
                    for document in snapshot!.documents {
                        let data = document.data()
                        let newEntry = Category(
                            title: data["title"] as! String,
                            photoKeyHome: data["photoKeyHome"] as! String
                          
                        )
                        
                            
                            
                            
                        self.filteredData
                            .append(newEntry)
                    }
                }
                DispatchQueue.main.async {
                    self.homeTableView.reloadData()
                }
            }
        }

TableView After tried to search

after I deleted what I searched


Solution

  • As mentioned in the comments datas is never been set. In getDatabaseRecords replace

    DispatchQueue.main.async {
       self.homeTableView.reloadData()
    }
    

    with

    DispatchQueue.main.async {
       self.datas = self.filteredData
       self.homeTableView.reloadData()
    }
    

    By the way your textDidChange method is very inefficient. Replace it with

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {        
        if searchText.isEmpty {
            filteredData = datas
        } else {
            filteredData = datas.filter{ $0.title.range(of: searchText, options: .caseInsensitive) != nil  }
        }
        self.homeTableView.reloadData()
    }