Google search from iPhone app

I want the user to enter a keyword in my application, and then search Google for that keyword, execute some logic of the results, and output the final output to the user.

Is it possible? How to do a Google search from my application? What is the response format? If anyone has some code examples for this, they will be greatly appreciated.

Thanks,

+4
source share
1 answer

A RESTful request for Google AJAX returns a response in JSON .

You can send an ASIHTTPRequest request and parse the JSON response on the iPhone using the json-framework .

For example, to create and submit a search request based on an example on a Google AJAX page, you can use the ASIHTTPRequest -requestWithURL and -startSynchronous :

 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 have built an instance of NSURL based on search queries, escaping query parameters.

If I followed the example of Google in the letter, I would also add this API key to it. Google asks you to use the API key for the search, but apparently it is not required. You can subscribe to the API key here .

There are also asynchronous request methods, which are described in detail in the ASIHTTPRequest documentation. You would use them so that the iPhone user interface is not tied during a search request.

Once you have a JSON response in hand format, 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 must also specify the IP address of the abstract in the request header, which in this case will be the local IP address of the iPhone, for example:

 - (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]; } 
+10
source

Source: https://habr.com/ru/post/1307918/


All Articles