Google parsing to autocomplete XML on iPhone

I am trying to run Google Autocomplete in my application, but I am having problems. For this, I use the delegate method UISearchBar and textDidChange . When the text changes, I use NSXmlParser to read an XML file like this:

 <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 will be the text of the UISearchBar. This returns an XML file, which I 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 do this.

+4
source share
1 answer

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

Then, in the 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 the parserDidEndDocument: delegate parserDidEndDocument: be sure to do everything you need to do to display it - it depends on which object your parser delegate is. If the parser delegate is a table view controller, you can simply reload the table. If this is some kind of request object, you can call back the request delegate, execute the completion block or post a notification.

+3
source

All Articles