我想让用户在我的应用中输入一个关键字,然后在 google 中搜索该关键字,对结果执行一些逻辑并向用户显示最终结论。
这可能吗?如何从我的应用程序执行 Google 搜索?回复的格式是什么?如果有人有一些这方面的代码示例,他们将不胜感激。
谢谢
最佳答案
一个RESTful search request to Google AJAX在 JSON 中返回响应格式。
您可以使用 ASIHTTPRequest 发出请求并在 iPhone 上使用 json-framework 解析 JSON 格式的响应.
例如,要创建并提交基于 Google AJAX 页面上的示例的搜索请求,您可以使用 ASIHTTPRequest 的 -requestWithURL
和 -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];
您将根据您的搜索词构建 NSURL
实例 escaping请求参数。
如果我严格遵循 Google 的示例,我还会向该网址添加 API key 。 Google 要求您使用 API key 进行搜索,但显然这不是必需的。您可以注册API key here .
还有异步请求方法,ASIHTTPRequest 文档中有详细介绍。您可以使用它们来防止 iPhone UI 在发出搜索请求时陷入困境。
一旦您掌握了 Google 的 JSON 格式的响应,您就可以使用 json-framework SBJSON
解析器对象将响应解析为 NSDictionary
对象:
NSError *requestError = [googleRequest error];
if (!requestError) {
SBJSON *jsonParser = [[SBJSON alloc] init];
NSString *googleResponse = [googleRequest responseString];
NSDictionary *searchResults = [jsonParser objectWithString:googleResponse error:nil];
[jsonParser release];
}
您还应该在请求 header 中指定引用 IP 地址,在本例中为 iPhone 的本地 IP 地址,例如:
- (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];
}
关于iphone - 在 iPhone 应用程序中进行 Google 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2707473/