0
votes

The search bar in my app isn't working. Ive narrowed down the problem to the method cellforRowAt. It's not able to show the search result when words are typed in. The cellforRowAt contains the information of the filtered articles in the indexpath. How do I resolve this ?

Project Link: https://github.com/lexypaul13/Covid-News.git

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //determines what data source should be used when user types

        if isFiltering{

            return filteredArticles?.count ?? 0

    }

        return articles?.count ?? 0



    }

    
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell

        let news: Articles

        filteredArticles = articles

        if isFiltering{

            news = filteredArticles![indexPath.row]

        }

        else{

            news = articles![indexPath.row]

        }

        cell.authorName.text = filteredArticles?[indexPath.row].author

        cell.headLine.text = filteredArticles?[indexPath.row].title

        cell.newsImage.downloadImage(from:(self.filteredArticles?[indexPath.item].urlImage ?? "nill"))

        cell.timePublication.text = filteredArticles?[indexPath.row].publishedAt



        if let dateString = filteredArticles?[indexPath.row].publishedAt,

        let date = indDateFormatter.date(from: dateString){

                   let formattedString = outDateFormtter.string(from: date)

                   cell.timePublication.text = formattedString

               } else {

                   cell.timePublication.text = "----------"

               }

        

               return cell

           }
   

    func updateSearchResults(for searchController: UISearchController) {

        let searchBar = searchController.searchBar

        filterContentForSearchText(searchBar.text!, articles!)

    }

    func filterContentForSearchText(_ searchText:String ,_ category: [Articles]){

        filteredArticles =  articles?.filter({ (article:Articles) -> Bool in

            return article.description.lowercased().contains(searchText.lowercased())

            

        })

        table_view.reloadData()

    }

     

 

1

1 Answers

1
votes

The problem in your code is the line return article.description.lowercased().contains(searchText.lowercased()) In this line the article.description gives you the description of the whole object and is a method of NSObjectProtocol.

So for this scenario you need to know on which item you need to search to get the filtered result. I looked at the code and got to know that the Articles contains title as a parameter. You can use this for filtering your search

So the code should change toreturn (article.title?.lowercased().contains(searchText.lowercased()) ?? false).