Tutorial details

Search for Product | App Code for Sale | Preview

Search for Product | iOS Tutorial

This tutorial is based on the component Search for Product
Download

Overview PAGE TOP

Demonstrates how to search the contents of a UITableView using UISearchBar and UISearchDisplayController, effectively filtering in and out the contents of that table. If an iPhone/iPod Touch application has large amounts of table data, this sample shows how to filter it down to a manageable amount if memory usage is a concern or you just want users to scroll through fewer tables content.

Project Set-Up: PAGE TOP

Create new project in XCode that will use single view application template and name it as ‘ProductSearch’. Ensure that you have the Use Automatic Reference Counting option checked as shown below.

119.png

263.png

Programming: PAGE TOP

Go to the AppDelegate.h file and add the UINavigation Controller, add property and synthesize it.

`@property (strong, nonatomic) UINavigationController *navigationController;`

Go to the AppDelegate.m file and modify the following code for the UINavigation Controller:

@synthesize navigationController = _navigationController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    return YES;
}

In ViewController.m file, in ViewDidLoad add the title for the Navigation Bar:

    self.title = @"Search Mobile Products";

Go to ViewController.xib, delete the existing view. Add the UITableView and Search Bar and Search Display controller to the XIB file and make sure that UITableView contains the search bar so that UITableView has the search bar on top of it as shown below.

379.png

466.png

Add the Scope Bar titles to the search bar, select search bar and enable the show scope bar and add the titles as ‘All’, ‘iOS’, ‘Andriod’ and ‘Windows 7’ (If you want to add the new category you can press on ‘+’ below the Show scope bar and new category and vice-versa), after saving the file don’t forgot to disable the show scope bar as shown:

557.png
Go to ProductSearch group/File, right click select ‘New File’, select create new file name it as ‘Product’ with the extension as NSObject.

630.png

In Product.h, create an instance for Product name and type:

@interface Product : NSObject {
    NSString *type;
    NSString *name;
}

@property (nonatomic, copy) NSString *type, *name;

+ (id)productWithType:(NSString *)type name:(NSString *)name;

@end

Product.m, implement the following method:

@synthesize type, name;

+ (id)productWithType:(NSString *)type name:(NSString *)name
{
    Product *newProduct = [[self alloc] init];
    newProduct.type = type;
    newProduct.name = name;
    return newProduct;
}
In ViewController.h, add the following instances:

#import "Product.h"
@interface ViewController : UIViewController<UISearchDisplayDelegate, UISearchBarDelegate>
{
    NSArray         *listContent;           
    NSMutableArray  *filteredListContent;   
    NSString        *savedSearchTerm;
    NSInteger       savedScopeButtonIndex;
    BOOL            searchWasActive;
}

@property (nonatomic, retain) NSArray *listContent;
@property (nonatomic, retain) NSMutableArray *filteredListContent;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, copy) NSString *savedSearchTerm;
@property (nonatomic) NSInteger savedScopeButtonIndex;
@property (nonatomic) BOOL searchWasActive;

@end
The above code states 

1. ListContent Array stores the list of mobile products 2. FilteredListContent stores the list of the user filtered products 3. savedSearchItem saves the user search entered text 4. savedScopeButtonIndex saves the filter such as All/iOS/Andriod/Wnidows 7 (1,2,3,4) of the product 5. searchWasActive, returns YES when search is enabled

Go to ViewController.m add the following methods:

@synthesize listContent, filteredListContent, savedSearchTerm, savedScopeButtonIndex, searchWasActive, tableView;

viewDidLoad --Called after the controller’s view is loaded into memory.

- (void)viewDidLoad
{
    self.title = @"Mobile Products";

    // create a filtered list that will contain products for the search results table.
    self.filteredListContent = [NSMutableArray arrayWithCapacity:[self.listContent count]];

    // restore search settings if they were saved in didReceiveMemoryWarning.
    if (self.savedSearchTerm)
    {
        [self.searchDisplayController setActive:self.searchWasActive];
        [self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
        [self.searchDisplayController.searchBar setText:savedSearchTerm];

        self.savedSearchTerm = nil;
    }

    [self.tableView reloadData];
    self.tableView.scrollEnabled = YES;
}

viewDidDisappear --Notifies the view controller that its view was removed from a view hierarchy.

- (void)viewDidDisappear:(BOOL)animated
{
    // save the state of the search UI so that it can be restored if the view is re-created
    self.searchWasActive = [self.searchDisplayController isActive];
    self.savedSearchTerm = [self.searchDisplayController.searchBar text];
    self.savedScopeButtonIndex = [self.searchDisplayController.searchBar selectedScopeButtonIndex];
}
If the requesting table view is the search display controller's table view, return the count of the filtered list, otherwise return the count of the main list.

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

        if (tableView1 == self.searchDisplayController.searchResultsTableView)
        {
            return [self.filteredListContent count];
        }
        else
        {
            return [self.listContent count];
        }
    }

If the requesting table view is the search display controller's table view, configure the cell using the filtered content, otherwise use the main list.

    - (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *kCellID = @"cellID";

        UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:kCellID];
        if (cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }

        Product *product = nil;
        if (tableView1 == self.searchDisplayController.searchResultsTableView)
        {
            product = [self.filteredListContent objectAtIndex:indexPath.row];
        }
        else
        {
            product = [self.listContent objectAtIndex:indexPath.row];
        }

        cell.textLabel.text = product.name;
        return cell;
    }

If the requesting table view is the search display controller's table view, configure the next view controller using the filtered content, otherwise use the main list.

- (void)tableView:(UITableView *)tableView1 didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIViewController *detailsViewController = [[UIViewController alloc] init];

    Product *product = nil;
    if (tableView1 == self.searchDisplayController.searchResultsTableView)
    {
        product = [self.filteredListContent objectAtIndex:indexPath.row];
    }
    else
    {
        product = [self.listContent objectAtIndex:indexPath.row];
    }
    detailsViewController.title = product.name;
    detailsViewController.view.backgroundColor = [UIColor whiteColor];
    [[self navigationController] pushViewController:detailsViewController animated:YES];
}

Update the filtered array based on the search text and scope. Search the main list for products whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array.

    - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
    {

        [self.filteredListContent removeAllObjects]; // First clear the filtered array.

        for (Product *product in listContent)
        {
            if ([scope isEqualToString:@"All"] || [product.type isEqualToString:scope])
            {
                NSComparisonResult result = [product.name compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
                if (result == NSOrderedSame)
                {
                    [self.filteredListContent addObject:product];
                }
            }
        }
    }

// Return YES to cause the search result table view to be reloaded.

        - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
        {
            [self filterContentForSearchText:searchString scope:
             [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
            return YES;
        }

// Return YES to cause the search result table view to be reloaded.

        - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
        {
            [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
             [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];

            return YES;
        }

In AppDelegate.m, applicationDidFinishLaunching method, Stores the list of the products into an array. If you want to add a new product you can always do the addObject to array as hown below:

NSArray *listContent = [[NSArray alloc] initWithObjects:
                         [Product productWithType:@”iOS” name:@”iPhone 3GS”],
                         [Product productWithType:@”iOS” name:@”iPod”],
                         [Product productWithType:@”iOS” name:@”iPhone 4S”],
                         [Product productWithType:@”iOS” name:@”iPad”],
                         [Product productWithType:@”iOS” name:@”iPod Touch”],
                         [Product productWithType:@”iOS” name:@”iPhone 4”],
                         [Product productWithType:@”iOS” name:@”iPhone 3”],
                         [Product productWithType:@”Andriod” name:@”Samsung Galaxy S2”],
                         [Product productWithType:@”Andriod” name:@”HTC Sensation”],
                         [Product productWithType:@”Andriod” name:@”Dell Venue”],
                         [Product productWithType:@”Andriod” name:@”Samsung Galaxy Note”],
                         [Product productWithType:@”Andriod” name:@”Motorola RAZR”],
                         [Product productWithType:@”Andriod” name:@”Samsung Galaxy Y”],
                         [Product productWithType:@”Andriod” name:@”HTC wild fire”],
                         [Product productWithType:@”Andriod” name:@”Acer Liquid E”],
                         [Product productWithType:@”Andriod” name:@”Huawei Ideos”],
                         [Product productWithType:@”Andriod” name:@”Sony Ericsson Xperia”],
                         [Product productWithType:@”Andriod” name:@”Motorola Fire”],   
                         [Product productWithType:@”Andriod” name:@”HTC Desire HD”],
                         [Product productWithType:@”Andriod” name:@”Micromax A70”],
                         [Product productWithType:@”Andriod” name:@”LG Optimus 3D”],
                         [Product productWithType:@”Andriod” name:@”Samsung Galaxy Ace”],
                         [Product productWithType:@”Andriod” name:@”Videocon Zeus Evolve”],
                         [Product productWithType:@”Windows 7” name:@”Nokia Lumia 800”],
                         [Product productWithType:@”Windows 7” name:@”HTC 7 Mozart”],
                         [Product productWithType:@”Windows 7” name:@”Dell Venue Pro”],
                         [Product productWithType:@”Windows 7” name:@”HTC Radar”],
                         [Product productWithType:@”Windows 7” name:@”HTC Titan”],
                         [Product productWithType:@”Windows 7” name:@”Samsung Omnia 7”], nil];


self.viewController.listContent = listContent;

Building and Running the application: PAGE TOP

The final step is to build and run the application. Click on the Build and Run button located in the toolbar of the main Xcode project window. Assuming an absence of compilation errors, the application should load into the iOS Simulator environment. Search the mobile phones by filtering the OS.

Home Screen Search for Mobile Products

1257.png

Tap on Search and select the category

1342.png
Search an item using keywords

1485.png

Details of the product, you can display anything here images and text based upon your requirement.

1532.png

4 Comments Leave a comment

Please login in order to leave a comment.

Newest first
  • engr.aamirwazir 2013-06-14 14:17:21 Thread #40

    how to recieved the message about a place when a person enterd in that area of the place i.e Resturants , hotels and update list of the meal menu is recieved on the person iphone mobile

  • engr.aamirwazir 2013-06-14 14:15:23 Thread #39

    i want complete ios notification tutorials also

  • engr.aamirwazir 2013-06-14 14:14:36 Thread #38

    hi

  • jaykingster.akasuki 2013-02-05 13:02:28 Thread #31

    how to add details in detail view pages

!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.