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];
}
19
  • Take a look at regex. Commented Dec 28, 2016 at 5:49
  • 1
    As per your code, Server end requires to do work for the parameter you send. There is no work for front-end. Commented Dec 28, 2016 at 5:58
  • 1
    Implement a search bar on top your UIViewController, allow user to type whatever he/she desires. And as per your requirement perform search on either pressing search button or change in character. Pass the value to the API and then show the response in a UITableView Commented Dec 28, 2016 at 6:00
  • 1
    Check this stackoverflow.com/questions/18719517/…. In delegate method you can call method that have above code. As user write the letter in search bar the method will be call. Try that and update the code. Then I can check where the problem because i don't know your all requirements yet. Commented Dec 28, 2016 at 6:41
  • 1
    @Amanpreet :) :) Your guidance. Thank You :) Commented Dec 28, 2016 at 9:36

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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];

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.