Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google search from within an iPhone app

I want to have the user enter a keyword in my app and then search google for this keyword, perform some logic on the results and display a final conclusion to the user.

Is this possible? How do I perform the search on google from my app? What is the format of the reply? If anybody has some code samples for this, they would be greatly appreciated.

Thanks,

like image 467
Rony Rozen Avatar asked Dec 29 '22 18:12

Rony Rozen


1 Answers

A RESTful search request to Google AJAX returns a response in JSON format.

You can issue the request with ASIHTTPRequest and parse the JSON-formatted response on an iPhone with json-framework.

For example, to create and submit a search request that is based on the example on the Google AJAX page, you could use ASIHTTPRequest's -requestWithURL and -startSynchronous methods:

NSURL *searchURL = [NSURL URLWithString:@"http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton"];
ASIHTTPRequest *googleRequest = [ASIHTTPRequest requestWithURL:searchURL];
[googleRequest addRequestHeader:@"Referer" value:[self deviceIPAddress]]; 
[googleRequest startSynchronous];

You would build the NSURL instance based on your search terms, escaping the request parameters.

If I followed Google's example to the letter, I would also add an API key to this URL. Google asks that you use an API key for searches, but apparently it is not required. You can sign up for an API key here.

There are also asynchronous request methods which are detailed in the ASIHTTPRequest documentation. You would use those to keep the iPhone UI from getting tied up while the search request is made.

Once you have Google's JSON-formatted response in hand, you can use the json-framework SBJSON parser object to parse the response into an NSDictionary object:

NSError *requestError = [googleRequest error];
if (!requestError) {
    SBJSON *jsonParser = [[SBJSON alloc] init];
    NSString *googleResponse = [googleRequest responseString];
    NSDictionary *searchResults = [jsonParser objectWithString:googleResponse error:nil];
    [jsonParser release];
}

You should also specify the referer IP address in the request header, which in this case would be the local IP address of the iPhone, e.g.:

- (NSString *) deviceIPAddress {
    char iphoneIP[255];
    strcpy(iphoneIP,"127.0.0.1"); // if everything fails
    NSHost *myHost = [NSHost currentHost];
    if (myHost) {
        NSString *address = [myHost address];    
        if (address)
            strcpy(iphoneIP, [address cStringUsingEncoding:NSUTF8StringEncoding]);
    }
    return [NSString stringWithFormat:@"%s",iphoneIP]; 
}
like image 158
Alex Reynolds Avatar answered Jan 05 '23 03:01

Alex Reynolds