Thursday, November 24, 2022
HomeiOS Developmentios - Unable to filter Json array from tableview with searchbar in...

ios – Unable to filter Json array from tableview with searchbar in swift


I’m utilizing tableview to point out Json knowledge and i’m utilizing searchbar to go looking a product from tableview

JSON construction: that is my api response for productslist

{
"outcome": {
    "merchandise": [
        {
            "name": "phone1",
        },
        {
            "city": "apple",
        },
        {
            "city": "android",
        },
        {
            "city": "samsung",
        },
        

code: here i am able to show and select product from tableview but unable to search the product using searchbar, why? where am i wrong. please guide me

var isSearching = false
var searchedProduct = [String]()

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

if searchText.rely != 0 {
    
    for eachData in productList ?? []{
        
        let vary = eachData.identify?.filter({$0.lowercased().prefix(searchText.rely) == searchText.lowercased()})
        if vary != nil {
            searchedProduct.append(eachData.identify ?? "")
        }
    }
    
    isSearching = true
}
productTableview.reloadData()
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
isSearching = false
searchBar.textual content = ""
productTableview.reloadData()
}




func tableView(_ tableView: UITableView, numberOfRowsInSection part: Int) -> Int {
if isSearching {
    return searchedProduct.rely
} else {
    return productList?.rely ?? 0
}
}

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

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

if isSearching {
    cell.nameLabel.textual content = searchedProduct[indexPath.row]
} 
else {
    let merchandise = productList?[indexPath.row]
    cell.nameLabel.textual content = merchandise?.identify
}

return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

if isSearching {
    productTF.textual content = searchedCountry[indexPath.row]
}
else{
    productTF.textual content = (productList?[indexPath.row].identify)
}

}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments