iphone - 在 iPhone 应用程序中进行 Google 搜索

标签 iphone search google-data-api

我想让用户在我的应用中输入一个关键字,然后在 google 中搜索该关键字,对结果执行一些逻辑并向用户显示最终结论。

这可能吗?如何从我的应用程序执行 Google 搜索?回复的格式是什么?如果有人有一些这方面的代码示例,他们将不胜感激。

谢谢

最佳答案

一个RESTful search request to Google AJAXJSON 中返回响应格式。

您可以使用 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/

相关文章:

java - 使用 A* 算法识别最便宜的路径

youtube - 从网络应用程序到youtube的Google API访问

iphone - iPhone 上的 FMS 相当于什么?

iphone - 更新后导航栏标题显示在后退按钮项上

ios - 在 Objective C 中,如何使用 CATileLayer 进行分页聚类

iphone - 旋转 UI 图像?

linux - 如果每行中的字符串匹配,则合并两个文件的内容

search - 如何将2个过滤器应用于ElasticSearch查询对象?

python - 使用 gdata-python-client 下载 Google 站点页面内容提要

c# - Google 日历 API 和工具是否允许您将数据保存在个人数据库中