Hi all, today we will discuss about search bar & how search bar displays search results from API in iOS, I'll skip some basics and lets suppose u have a tableView which already has some data lets suppose record of names of students, So without discussing much about table view lets talk about search bar & getting its results from an API.
Here are the steps hope it helps-
1. Add a UISearchbar & create its IBOutlet in your ViewController, let's suppose UISearchbar *mysearchBar;
2. Drag the searchbar to top & give its delegate also add <UISearchBarDelegate,UISearchDisplayDelegate> in your ViewController.
3. Add placeholder as a search on the searcher.
4. Now all you have to do is get the alphabets that are entered in searchbar & use those alphabets as param for your searcAPIpi.
5. So when you hit the API or lets say you have searched “x” in the searchbar then the API will return the response of student names such as Xander, Xavier, etc & all you have to do is display the response from the API into the tableview that earlier contained all students name it should now display names started with “x” or whatever you have searched.
I hope the basic functionality is clear by now so let's jump in the code now-
Once the Search-bar delegates are added you can now use search-bar delegate methods-
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
// Do the search...
And once this api i.e “serverHitToSearch” returns the response you can then display it in your tableview.
NOTE- In the above function we have also checked if there is any value or alphabet that we have to search so if the searchbar is empty u can show a popup alert. Secondly, you have to reload your initial TableView once the user clicks on the Cancel button of Searchbar & remove the alphabets that you have typed when you wanted to search.There are some more searchbar delegate methods you can use them according to your requirements.