4

I'm trying to get Google search autocomplete working in my app, but I've run into some trouble. I'm using a UISearchBar and it's textDidChange delegate method to do so. When the text changes, I use NSXmlParser to read an XML file like this one:

<toplevel>
<CompleteSuggestion>
<suggestion data="searchterms"/>
<num_queries int="13400000"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="searchterms twitter"/>
<num_queries int="52500000"/>
</CompleteSuggestion>
</toplevel>

http://suggestqueries.google.com/complete/search?client=toolbar&q=SEARCHTERM

Where SEARCHTERM would be the UISearchBar text. This returns an XML file, which I would then parse to find the suggested term using

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict

but I'm not quite sure how to.

Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
JohnWickham
  • 571
  • 1
  • 6
  • 15

1 Answers1

3

The general idea is to have a searchSuggestions mutable array property. In the parserDidStartDocument: method, make sure to initialize it to a new, empty array - something like self.searchSuggestions = [NSMutableArray array];.

Then, in your didStartElement delegate method, do this to get each suggested item.

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    if ([elementName isEqualToString:@"suggestion"]) {
        NSString *suggestion = attributeDict[@"data"];
        [self.searchSuggestions addObject:suggestion];
    }
}

Once you get your parserDidEndDocument: delegate callback, make sure to do whatever you need to do to display it - it depends on what object is your parser delegate. If your parser's delegate is a table view controller, you could just reload the table. If it's some request object, you could call back to the request's delegate, execute a completion block, or post a notification.

Carl Veazey
  • 18,392
  • 8
  • 66
  • 81