Implementing Google Suggestions into your iOS App

Have you ever thought of implementing google suggestions into your iOS App ?

Sample Output.

Google Suggestions into your iOS App output

Sample Output video.

If you are looking for the same, this post is for you. Just go through the post details to understand the implementation.

1. Open your project. Open your user interface of view controller. Design it as follow ( or may be as per your need. This user interface is just for an example ).
sugartin Implementing Google Suggestions into your iOS App UI

2. Now apply appropriate connections to your .h class. Add properties for an array & an ASIHttpRequest.
( One may use any other pattern for making web-service calls. Here I have used ASIHTTPRequest ).
Here is the sample snap of .h file of viewController, so you can have clear idea.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
#import <uikit /UIKit.h>
#import "ASIHTTP/ASIHTTPRequest.h"
@interface STViewController : UIViewController <uisearchbardelegate ,
    UITableViewDataSource,
    UITableViewDelegate,
    ASIHTTPRequestDelegate>

@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
@property (strong, nonatomic) ASIHTTPRequest *req;
@property (strong, nonatomic) NSMutableArray *arForTable;
@end

3. As I have used UISearchBar, I will be placing code for making request in UISearchBarDelegate Methods. Go through the code with comments.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    // obtain the text to be search from UISearchBar
    NSString *strSearch = self.searchBar.text ;
    // trim the spaces
    strSearch = [strSearch stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    // ensure the lenght of text
    if(strSearch && strSearch.length) {
        // create a URL
        strSearch = [@"http://google.com/complete/search?output=toolbar&q=" stringByAppendingString:strSearch];
        // add PercentEscapes
        strSearch = [strSearch stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        // cancel previous requests if any
        if(self.req) {
            self.req.delegate=nil;
            [self.req cancel];
            self.req=nil;
        }
        // create new request
        self.req = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:strSearch]];
        self.req.delegate=self;
        // start async call
        [self.req startAsynchronous];
    } else {
    // if search text length is 0
        // cancel previous request
        if(self.req) {
            self.req.delegate=nil;
            [self.req cancel];
            self.req=nil;
        }
        // remove all objects & hide the table.
        if(self.arForTable && self.arForTable.count) {
            [self.arForTable removeAllObjects];
            [self.tableView reloadData];
            self.tableView.hidden=YES;
        }
    }
}

4. Following is the code for parsing & adding data into array. after adding data into array, table will get reload.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
- (void)requestFailed:(ASIHTTPRequest *)request {
    NSLog(@"request failed %@",[request responseStatusMessage]);
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    // after receiving response remove all previous data
    if(self.arForTable && self.arForTable.count) {
        [self.arForTable removeAllObjects];
        [self.tableView reloadData];
        self.tableView.hidden=YES;
    }
    // create empty array
    self.arForTable=[NSMutableArray array];
    
    // logic for parsing beings ----
    // create DOM document
    CXMLDocument *doc = [[CXMLDocument alloc] initWithData:[request responseData] encoding:[request responseEncoding] options:0 error:nil];
    // grab child nodes of topLevel
    NSArray *ar = [doc nodesForXPath:@"//toplevel/*" error:nil];
    for (CXMLNode *node in ar) {
        NSString *strNodeName = [node name];
        if(strNodeName && [strNodeName isKindOfClass:[NSString class]] && strNodeName.length && [strNodeName isEqualToString:@"CompleteSuggestion"]) {
            // grab child nodes of CompleteSuggestion
            NSArray *arInnerNodes = [node children];
            for (CXMLNode *nodeInner in arInnerNodes) {
                strNodeName = [nodeInner name];
                if(strNodeName && [strNodeName isKindOfClass:[NSString class]] && strNodeName.length && [strNodeName isEqualToString:@"suggestion"]) {
                    // grab suggestion node attribues
                    CXMLElement *element = (CXMLElement*)nodeInner;
                    NSArray *attr = [element attributes];
                    for (CXMLNode *nodeAttr in attr) {
                        strNodeName = [nodeAttr name];
                        if(strNodeName && [strNodeName isKindOfClass:[NSString class]] && strNodeName.length && [strNodeName isEqualToString:@"data"] && [nodeAttr stringValue] && [[nodeAttr stringValue] isKindOfClass:[NSString class]] && [[nodeAttr stringValue] length]) {
                            // grab value of attribute named 'data' & add it into an array
                            [self.arForTable addObject:[nodeAttr stringValue]];
                        }
                    }
                }
            }
        }
    }
    // logic for parsing over ---------
    
    // reload table
    if(self.arForTable && self.arForTable.count) {
        [self.tableView reloadData];
        self.tableView.hidden=NO;
    }
}

5. Grab the complete source code from here.

This post is written to answer to the question from stackoverflow.com.

Did you like this? Share it:

About Sagar R. Kothari

Hey ! Hi there ! I am Sagar R. Kothari. I am graduated from Gujarat University. I am pursuing M.C.A from IGNOU University. I am in iOS App/Game Development since last 3 years. I am always hunting for better knowledge in iOS. I am looking forward to be a good app & game developer. I keep on sharing my knowledge @ http://sugartin.info as soon as I get spare time for it. I would love to hear your personal feedback about this blog.

Leave a Reply

Your email address will not be published. Required fields are marked *


nine × = 27

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">