Search code examples
iosobjective-csearchuisearchbaruisearchcontroller

iOS: How to implement search controller using objective c & How to call API at runtime i.e when I start typing in search controller?


I want to implement search controller like gmail application,

enter image description here

OR I want to implement like this example

enter image description here

Image 1 It shows normal inbox with search controller button

Image 2 After clicking on search button It will expand show like image 2. Here we can enter the words...etc

Image 3 Here whatever we enter, depending upon text it shows in list, and when we click on it, it will navigate to detail view.

same thing I want to implement.

Only thing is that, when I will start typing in search controller, one API will call i.e search, then depending upon text entered in search, it will take as parameter and it will show data in list (table view). this data will come from API response.

And when I click on any result, it has to move detail view.

Anybody, can help me.

I am totally new in iOS. Just now I started learning of iOS. Plz help me for this.

Here is .h file

#import <UIKit/UIKit.h>

@interface PDSearchExampleTableViewController : UITableViewController
{
    BOOL searching;
}

@property (strong, nonatomic) UISearchBar *searchBar;
@property (strong, nonatomic) NSMutableArray *sampleDataArray;
@property (strong, nonatomic) NSMutableArray *filteredSampleDataArray;


- (IBAction)searchButtonClicked:(id)sender;

@end

Here is .m file

#import "PDSearchExampleTableViewController.h"

@interface PDSearchExampleTableViewController () <UISearchDisplayDelegate, UISearchBarDelegate>

@end

@implementation PDSearchExampleTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _searchBar.delegate = self;
    _sampleDataArray = [[NSMutableArray alloc] init];
    _filteredSampleDataArray = [[NSMutableArray alloc] init];
    [_sampleDataArray addObject:@"one"];
    [_sampleDataArray addObject:@"two"];
    [_sampleDataArray addObject:@"three"];
    [_sampleDataArray addObject:@"four"];
    [_sampleDataArray addObject:@"five"];
    [_sampleDataArray addObject:@"six"];
    [_sampleDataArray addObject:@"seven"];



     [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (searching) {
        return [_filteredSampleDataArray count];
    } else {
        return [_sampleDataArray count];
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sampleSearchCell" forIndexPath:indexPath];


    if (searching) {
        cell.textLabel.text = [_filteredSampleDataArray objectAtIndex:indexPath.row];
    } else {
        cell.textLabel.text = [_sampleDataArray objectAtIndex:indexPath.row];
    }

    return cell;
}

- (IBAction)searchButtonClicked:(id)sender {
    self.navigationItem.rightBarButtonItem = nil;
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.delegate = self;
    _searchBar.placeholder = @"Search Sample Data";
    [_searchBar sizeToFit];
    self.navigationItem.titleView = _searchBar;
    [_searchBar becomeFirstResponder];
    [_searchBar.window makeKeyAndVisible];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [_searchBar setShowsCancelButton:YES animated:YES];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {

}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searching = NO;
    [self.tableView reloadData];
    self.navigationItem.titleView = nil;
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchButtonClicked:)];
    [_searchBar setShowsCancelButton:NO];
    [_searchBar resignFirstResponder];
    self.navigationItem.rightBarButtonItem = rightBarButton;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [_filteredSampleDataArray removeAllObjects];

    if ([searchText length] != 0) {
        searching = YES;
        [self searchData];
    } else {
        searching = NO;
    }

    [self.tableView reloadData];
}

- (void)searchData {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@", _searchBar.text];
    NSArray *tempArray = [_sampleDataArray filteredArrayUsingPredicate:predicate];
    NSLog(@"%@", tempArray);
    _filteredSampleDataArray = [NSMutableArray arrayWithArray:tempArray];
}

Solution

  • Follow the below steps, it will work definitely not exactly as same as your screenshots.

    STEP 1: Create a navigation button on the navigation bar and add image button of a search for it. This can be done by using a storyboard or using programmatically.

    Give action to that button,

    - (IBAction)searchButtonAction:(id)sender {
    
        SearchViewController *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"id1"];
        [self.navigationController pushViewController:vc animated:YES];
    
    }
    

    after clicking this button, it will navigate to SearchViewController view.

    See storyboard, design like below image

    enter image description here

    and write below code in SearchViewController,

    Create IBOutlet of textField and give action to the search button, and add tableView and add delegates and data source for it.

      @property (weak, nonatomic) IBOutlet UITextField *seachTextField;
    
      @property (weak, nonatomic) IBOutlet UITableView *tableview1;
    

    and

    - (BOOL)textFieldShouldReturn:(UITextField *)textField
        {
            [_seachTextField resignFirstResponder];
            return YES;
        }
    
    
    // This method asks the delegate whether the specified text should be replaced in the text view.
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
    
        NSLog(@"Search String is : %@",_seachTextField.text);
        NSString *dataFromSearchTextField=[NSString stringWithFormat:@"%@",_seachTextField.text];
    
    
        return YES;
    }
    
    
    
    
    - (IBAction)searchButtonAction:(id)sender {
    
       // call method for which takes search string
    
        [self ApiMethodCall:_seachTextField.text];
     }
    
    
    //After clicking on search button, below method is called i.e t API is called
    -(void)ApiMethodCall:(NSString *)searchText
    {
    
        // call your API with parameters
        // you will get JSON
    
    }
    

    that's it, now it is your turn. Take data from JSON which may contain arrays and dictionaries. Simply do JSON parsing and write table view data source and delegate methods and show data.