0

I want to use SearchBar where the elements are generated dynamically with the help of service. Like, if I will pass "i" as parameter, service will fetch all the elements which includes "i" as initial characters. I cannot retrieve the logic as how to implement that in code.

Below is the service am using to get data. But I don't know how to implement Search bar using it.

NSURL * url=[NSURL URLWithString:@"http://dealnxt.com/api/search?searchkey=i"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"Array is:%@",array);

Below i the code I tried :

.h file

#import <UIKit/UIKit.h>

@interface SearchViewController : UIViewController<UISearchDisplayDelegate,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UITextFieldDelegate>
{
    NSMutableArray *contentList;
    NSMutableArray *filteredContentList;
    BOOL isSearching;
}
@property (strong, nonatomic) IBOutlet UIView *SearchView;
@property (strong, nonatomic) IBOutlet UISearchBar *SearchBar;
@property (strong, nonatomic) IBOutlet UISearchDisplayController *Search;
@property (strong, nonatomic) IBOutlet UITableView *Content;

@end

.m file

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
 }

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (isSearching) {
    return [filteredContentList count];
}
else {
    return [contentList count];
}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

if (isSearching) {
    cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else {
    cell.textLabel.text = [[contentList objectAtIndex:indexPath.row] valueForKey:@"shortdescription"];

}
return cell;

}
- (void)searchTableList {
NSString *searchString = _SearchBar.text;

NSString *UrlString =[NSString stringWithFormat:@"http://dealnxt.com/api/search?searchkey=%@",searchString];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:[NSURL URLWithString:UrlString]];
[Request setHTTPMethod:@"GET"];
NSData *ReturnData = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];
NSString *str=[[NSString alloc]initWithData:ReturnData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
contentList=[jsonDict objectForKey:@"ProductDescriptionModel"];

    [filteredContentList addObject:[[contentList firstObject] valueForKey:@"shortdescription"]];

}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;

}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSLog(@"Text change - %d",isSearching);

//Remove all objects first.
[filteredContentList removeAllObjects];

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

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Cancel clicked");
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Search Clicked");
[self searchTableList];
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Shikha Sharma
  • 451
  • 1
  • 5
  • 25

2 Answers2

1

Here is the solution :

.h file #import

@interface SearchViewController : UIViewController<UISearchDisplayDelegate,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UITextFieldDelegate>
{
   NSMutableArray *contentList;
   NSMutableArray *filteredContentList;
   BOOL isSearching;
}
@property (strong, nonatomic) IBOutlet UIView *SearchView;
@property (strong, nonatomic) IBOutlet UISearchBar *SearchBar;
@property (strong, nonatomic) IBOutlet UISearchDisplayController *Search;
@property (strong, nonatomic) IBOutlet UITableView *Content;

@end

.m file

 #import "SearchViewController.h"
 #import "UIColor+HexString.h"

 @interface SearchViewController ()

 @end

 @implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _SearchView.backgroundColor=[UIColor colorWithHexString:@"#5130F7"];
   _SearchBar.barTintColor=[UIColor colorWithHexString:@"#5130F7"];
   _SearchBar.layer.borderWidth = 1;
   _SearchBar.layer.borderColor = [UIColor colorWithHexString:@"#5130F7"].CGColor;

   _Content.delegate=self;
   _Content.dataSource=self;
  }

 - (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];

 }

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
     return 1;
  }

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

   if (isSearching) {
    return [filteredContentList count];
}
  else {
    return [contentList count];
}
}

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

if (isSearching) {
    cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else {
    cell.textLabel.text = [[contentList objectAtIndex:indexPath.row] valueForKey:@"shortdescription"];

}
return cell;

}
- (void)searchTableList {
NSString *searchString = _SearchBar.text;

NSString *UrlString =[NSString stringWithFormat:@"http://abc.in/key?key=%@",searchString];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:[NSURL URLWithString:UrlString]];
[Request setHTTPMethod:@"GET"];
NSData *ReturnData = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];
NSString *str=[[NSString alloc]initWithData:ReturnData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
contentList=[jsonDict objectForKey:@"ProductDescriptionModel"];

filteredContentList =[contentList valueForKey:@"shortdescription"];


NSLog(@"filter:%@",filteredContentList);
[_Content reloadData];

}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;

}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSLog(@"Text change - %d",isSearching);

//[filteredContentList removeAllObjects];

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

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Cancel clicked");
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Search Clicked");
[self searchTableList];
}

 @end
Shikha Sharma
  • 451
  • 1
  • 5
  • 25
0

Easy way to search anything from dynamic array

your controller.m

{
NSMutableArray *contacts;
NSMutableArray *combinearray;
NSString *searchTextString;
NSMutableArray *searchArray;
BOOL isFilter;
}


- (void)viewDidLoad {
[super viewDidLoad];

txtSearchBar.backgroundColor=Clear;

txtSearchBar.layer.cornerRadius=2;
txtSearchBar.clipsToBounds=YES;
txtSearchBar.delegate =self;
txtSearchBar.layer.borderColor=Black.CGColor;
txtSearchBar.layer.borderWidth=2.0f;
[txtSearchBar addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
txtSearchBar.layer.sublayerTransform = CATransform3DMakeTranslation(20, 0, 0);

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.


if(isFilter)
{
    return [searchArray count];
}
else
return  arrCardsName.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(isFilter)
{
yourDictionary = [searchArray objectAtIndex:indexPath.row];
}

else

{
yourDictionary = [yourArray objectAtIndex:indexPath.row];
}

return cell;

}


-(void)textFieldDidChange:(UITextField*)textField
{
searchTextString = textField.text;

[self updateSearchArray:searchTextString];
}

-(void)updateSearchArray:(NSString *)searchText

{

if (searchText.length > 0)
{
    isFilter=YES;

    searchArray = [NSMutableArray array];
    searchText = [NSString stringWithFormat:@"%@",searchText];



    for ( NSDictionary* item in yourArray )
    {
        //NSLog(@"contacts ----->%@",[item objectForKey:@"city"]);

        if ([[[item objectForKey:@"city"] lowercaseString] rangeOfString:[searchText lowercaseString]].location != NSNotFound)//object for key @"do whatever you want to search"
        {

            [searchArray addObject:item];
        }
    }


}

if (!searchText || searchText.length == 0)
{
    isFilter=NO;
    searchArray = [yourArray mutableCopy];
}
else
{
    if ([searchArray count] == 0)
    {
        NSLog(@"No data From Search");
    }
}
// NSLog(@"search array ====>%@",searchArray);
[tbleView reloadData];

}
Dishant Rajput
  • 1,329
  • 1
  • 10
  • 20