谷歌在iPhone应用程序中搜索

Ron*_*zen 4 iphone search google-data-api

我希望让用户在我的应用中输入关键字,然后在谷歌搜索此关键字,对结果执行一些逻辑并向用户显示最终结论.

这可能吗?如何从我的应用程序在谷歌上执行搜索?回复的格式是什么?如果有人为此提供了一些代码示例,我们将不胜感激.

谢谢,

Ale*_*lds 10

一个RESTful的搜索请求,谷歌AJAX返回的响应JSON格式.

您可以使用ASIHTTPRequest发出请求,并使用json-framework在iPhone上解析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];
Run Code Online (Sandbox Code Playgroud)

您将NSURL根据搜索条件构建实例,并转义请求参数.

如果我按照Google的示例,我也会在此网址中添加API密钥.Google要求您使用API​​密钥进行搜索,但显然不需要.您可以在此处注册API密钥.

还有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];
}
Run Code Online (Sandbox Code Playgroud)

您还应该在请求标头中指定引用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]; 
}
Run Code Online (Sandbox Code Playgroud)